Do not make assumptions about the sign of the resulting value from the remainder % operator.
The result of the remainder operator is the remainder when the first operand is divided by the second. When the division is inexact, the result is determined by the following rules:
The sign of the remainder % operator is implementation-defined when the operands are of different sign. This can result in a portability problem, when the programmer has assumed that i % j is always positive.
i % j |
In division where either operand is negative, the direction of truncation is toward 0.
If either operation is negative in division with the remainder operator, the result has the same sign as the dividend (the first operand in the expression). For example:
50 % -6 = 2 -50 % 6 = -2 |
In each case, 50 and 2 have the same sign.
The result is the same sign as the dividend; thus, the remainder of -23/4 is -3.
To provide a true (never negative) modulo operation, use the IMOD ("integer modulo") macro:
/* modulo macro giving non-negative result */ #define IMOD(i, j) (((i) % (j)) < 0 ? ((i) % (j)) + (j) : ((i) % (J))) /* if i % j is never negative, replace with the following line: */ /* #define IMOD(i, j) ((i) % (j)) */ |
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
STR07-A |
1 (low) |
1 (unlikely) |
2 (medium) |
P2 |
L3 |
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[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] \[[Sun 05|AA. C References#Sun 05]\] C User's Guide Sun Studio 11 819-3688-10 http://docs.sun.com/source/819-3688/. 2005. [Appendix E, "Implementation-Defined ISO/IEC C90 Behavior"|http://docs.sun.com/source/819-3688/c90.implementation.app.html] |