In C89 (and historical K&R implementations), the meaning of the remainder operator for negative operands was implementation-defined. This behavior was changed in C99, and the change remains in C11.
Because not all C compilers are strictly C-conforming, you cannot rely on the behavior of the % operator if you need to run on a wide range of platforms with many different compilers.
The C Standard, Section section 6.5.5 [ISO/IEC 9899:2011], states:
...
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
Compass/ROSE |
|
| 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. | ||||||
Fortify SCA | 5.0 |
| Can detect violations of this recommendation with the CERT C Rule Pack. | ||||||
| 584 S | Fully implemented. | |||||||
| PRQA QA-C |
| 3103 | Fully implemented. |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
Bibliography
| [Beebe 2005] | |
| [ISO/IEC 9899:2011] | Section 6.5.5, "Multiplicative Operators" |
| [Microsoft 2007] | C Multiplicative Operators |
| [Sun 2005] | Appendix E, "Implementation-Defined ISO/IEC C90 Behavior" |
...