...
Because not all C compilers are strictly C-conforming, you programmers cannot rely on the behavior of the % operator if you they need to run on a wide range of platforms with many different compilers.
The C Standard, section subclause 6.5.5 [ISO/IEC 9899:2011], states:
The result of the
/operator is the quotient from the division of the first operand by the second; the result of the%operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.
...
In this noncompliant code 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 are 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.
...
The most appropriate solution in this case is to use unsigned types to eliminate any possible implementation-defined behavior, as in this compliant solution. For compliance with ERR02-C. Avoid in-band error indicators, we fill this solution fills a result argument with the mathematical result , and we return returns nonzero only if the operation succeeds.
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
|
| Could detect the specific noncompliant code example. It could identify when the result of a % operation might be negative and flag usage of that result in an array index. It could conceivably flag usage of any such result without first checking that the result is positive, but it would likely introduce many false positives | |||||||
5.0 |
| Can detect violations of this recommendation with the CERT C Rule Pack | |||||||
| 584 S | Fully implemented | |||||||
| PRQA QA-C |
| 3103 | Fully implemented |
...
Bibliography
| [Beebe 2005] | |
| [ISO/IEC 9899:2011] | Section Subclause 6.5.5, "Multiplicative Operators" |
| [Microsoft 2007] | C Multiplicative Operators |
| [Sun 2005] | Appendix E, "Implementation-Defined ISO/IEC C90 Behavior" |
...