If a while or for statement uses a loop counter, and increments or decrements it by more than one, it should use an inequality a numerical comparison operator to terminate the loop.
Noncompliant Code Example
This noncompliant code example may appear to have 5 iterations, but in fact, the loop never terminates because the value of i will increment from 1 to 3 to 5 to 7 to 9 to 11, skipping right over 10. Using 32-bit integers on a two's-complement machine, the value will reach the maximum representable positive number and then wrap to the second lowest negative number (an odd number). It will work its way up to -1, then 1, and proceed as at the beginning.
Code Block | ||
---|---|---|
| ||
for ( i = 1; i != 10; i += 2 ) { // ... } |
Noncompliant Code Example
This noncompliant code example will terminate (using 32-bit integers on a two's-complement machine), but only after many more iterations than expected. It will increment i from 1 to 6 to 11, skipping past 10. It will then wrap from near the maximum positive value to near the lowest negative value and work its way up toward zero. It will reach 2, 7, and 12, skipping 10 again. After the value wraps from high positive to low negative three more times, it will finally reach 0, 5, and 10, where the loop will terminate.
Code Block | ||
---|---|---|
| ||
for ( i = 1; i != 10; i += 5 ) { // ... } |
Compliant Solution
An inequality Using a numerical comparison operator guarantees proper loop termination.
Code Block | ||
---|---|---|
| ||
for ( i = 1; i <= 10; i += 2 ) { // ... } |
Risk Assessment
Testing for exact values runs the risk of a loop terminating after much longer than expected, or never terminating at all.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC36-J | low | unlikely | low | P1 | L3 |
Automated Detection
None.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This rule appears in the C Secure Coding Standard as MSC21-C. Use inequality to terminate a loop whose counter changes by more than one .
This rule appears in the C++ Secure Coding Standard as MSC21-CPP. Use inequality to terminate a loop whose counter changes by more than one.
References
Wiki Markup |
---|
\[[MISRA 04INT34-J. Perform explicit range checking to ensure integer operations do not overflow]\] \[[JLS 03|AA. CJava References#MISRAReferences#JLS 0403]\] 15.20.1 Numerical Comparison Operators <, <=, >, and >= |