Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
In C89 (and historical K&R [implementations|BB. Definitions#implementation]), the meaning of the remainder operator for negative operands was [implementation- defined|BB. Definitions#implementation- defined behavior]. This was changed in the C99 standard \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\].

...

Discarding the fractional part of the remainder is often called " truncation toward zero."

The C99 definition of the % operator implies the following behavior:

...

Non-Compliant Code Example

In this non-compliant noncompliant example, the insert() function adds values to a buffer in a modulo fashion, that is, by inserting values at the beginning of the buffer once the end is reached. However, both size and index are declared as int and consequently not guaranteed to be positive. Depending on the implementation , and on the sign of size and index, the result of (index + 1) % size may be negative, resulting in a write outside the bounds of the list array.

Code Block
bgColor#FFCCCC
int insert(int index, int *list, int size, int value) {
  if (size != 0) {
    index = (index + 1) % size;
    list[index] = value;
    return index;
  }
  else {
    return -1;
  }
}

This non-compliant noncompliant code example also violates INT01-C. Use rsize_t or size_t for all integer values representing the size of an object.

...

Wiki Markup
\[[Beebe 05|AA. C References#Beebe 05]\]
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.5.5, "Multiplicative operators"
\[[Microsoft 07|AA. C References#Microsoft 07]\] [C Multiplicative Operators|http://msdn2.microsoft.com/en-us/library/efa0csed(VS.80).aspx]
\[[MITRE 07|AA. C References#MITRE 07]\] [CWE ID 682|http://cwe.mitre.org/data/definitions/682.html], "Incorrect Calculation," and [CWE ID 129|http://cwe.mitre.org/data/definitions/129.html], "Unchecked Array Indexing"
\[[Sun 05|AA. C References#Sun 05]\] [Appendix E, "Implementation-Defined ISO/IEC C90 Behavior"|http://docs.sun.com/source/819-3688/c90.implementation.app.html]

...