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:
- If the right operand is zero, the result is undefined.
- If both operands are positive or unsigned, the result is positive.
- If either operand is negative and the result is inexact, the result is implementation defined.
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.
Non-Compliant Coding Example
i % j
Implementation Details
Microsoft Visual Studio
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.
Compliant Solution
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)) */
Risk Assessment
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
STR07-A |
1 (low) |
1 (unlikely) |
2 (medium) |
P2 |
L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
[[ISO/IEC 9899-1999]] Section 6.5.5, "Multiplicative operators"
[[Microsoft 07]] C Multiplicative Operators![]()
[[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"![]()