
...
The C definition of the %
operator implies the following behavior:
Code Block |
---|
1711 % 35 -> 21 1711 % -35 -> 21 -1711 % 35 -> -21 -1711 % -35 -> -21 |
The result has the same sign as the dividend (the first operand in the expression).
...
However, this noncompliant code example violates INT01-C. Use rsizesize_t or sizersize_t for all integer values representing the size of an object. There is also a possibility that (index + 1)
could result in a signed integer overflow in violation of INT32-C. Ensure that operations on signed integers do not result in overflow.
...
Code Block | ||||
---|---|---|---|---|
| ||||
int insert(size_t* result, size_t index, int *list, size_t size, int value) { if (size != 0 && size != SIZE_MAX) { index = (index + 1) % size; list[index] = value; *result = index; return 1; } else { return 0; } } |
Risk Assessment
Incorrectly assuming that the result of the remainder operator for signed operands will always be positive can lead to an out-of-bounds memory accessor other flawed logic.
Recommendation | Severity | Likelihood |
---|
Detectable | Repairable | Priority | Level |
---|---|---|---|
INT10-C | High |
Unlikely |
No |
No |
P3 | L3 |
Automated Detection
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 | |||
Helix QAC |
5.0
| C3103 | ||||||||
LDRA tool suite |
| 584 S | Fully implemented |
Parasoft C/C++test |
| CERT_C-INT10-a | The operands of the remainder operator '%' should be of unsigned integer types | ||||||
Polyspace Bug Finder |
| Checks for tainted modulo operand (rec. fully covered) |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
SEI CERT C++ |
Coding Standard | VOID INT10-CPP. Do not assume a positive remainder when using the % operator |
CERT Oracle Secure Coding Standard for Java | NUM02-J. Ensure that division and |
remainder operations do not result in divide-by-zero errors | |
MITRE CWE | CWE-682, Incorrect calculation CWE-129, Unchecked array indexing |
Bibliography
[Beebe 2005] |
[ISO/IEC 9899:2011] | Subclause 6.5.5, "Multiplicative Operators" |
[Microsoft 2007] | C Multiplicative Operators |
[Sun 2005] | Appendix E, "Implementation-Defined ISO/IEC C90 Behavior" |
...
...