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.
This noncompliant code example may appear to have 5 iterations, but in fact, the loop never terminates.
for ( i = 1; i != 10; i += 2 ) {
// ...
}
|
An inequality comparison guarantees loop termination.
for ( i = 1; i <= 10; i += 2 ) {
// ...
}
|
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 |
ROSE can detect violations of this rule.
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
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.
\[[MISRA 04|AA. C 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