Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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

Code Block
bgColor#FFCCCC
i % j

Implementation Details

Microsoft Visual Studio

In division where either operand is negative, the direction of truncation is toward 0.

...

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:

Code Block
bgColor#ccccff
/* 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

Wiki Markup
\[[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]