If a while or for statement uses a loop counter, and increments or decrements it by more than one, it should use an inequality 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.
for ( i = 1; i != 10; i += 2 ) { // ... }
Compliant Solution
An inequality comparison guarantees loop termination.
for ( i = 1; i <= 10; i += 2 ) { // ... }
Risk Assessment
Testing for exact values runs the risk of a loop terminating much longer than expected, or never terminating at all.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
MSC21-C |
low |
unlikely |
low |
P1 |
L3 |
Automated Detection
ROSE can detect violations of this rule.
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.
References
[[MISRA 04]]
MSC06-C. Be aware of compiler optimization when dealing with sensitive data 49. Miscellaneous (MSC) APP00-C. Functions should validate their parameters