Versions Compared

Key

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

Wiki Markup
If a {{while}} or {{for}} statement uses a loop counter, and increments or decrements it by more than one, it should use a numerical comparison operator to terminate the loop. This prevents the loop from running away, either forever, executing indefinitely or until the counter wraps around and reaches the final value (\[[INT34-J. Perform explicit range checking to ensure integer operations do not overflow]\]).

Noncompliant Code Example

This noncompliant code example may appear to have 5 iterations, but in fact, appears to iterate five times. However, the loop never terminates because the value successive values of i will increment from are 1 to , 3 to , 5 to , 7 to , 9 to and 11, skipping right over 10. Using 32-bit integers on a two's-complement machine, the value will reach allowing the comparison with 10 to be skipped. On a Java based system, the value reaches the maximum representable positive number and then wrap (Integer.MAX_VALUE) and on subsequent incrementing, wraps to the second lowest negative number (an odd numberInteger.MIN_VALUE - 1). It will work then works its way up to -1, then 1, and proceed as at the beginningproceeds as described earlier.

Code Block
bgColor#FFCCCC
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 terminates, but takes more iterations than expected. It will increment i from 1 to 6 to increments i so that it is 1, 6 and 11, skipping past 10. It will then wrap The value of i then wraps from near the maximum positive value to near the lowest negative value and work works its way up toward zero. It will reach assumes 2, 7, and 12, skipping past 10 again. After the value wraps from the high positive to the low negative side three more times, it will finally reach reaches 0, 5, and 10, where terminating the loop will terminate.

Code Block
bgColor#FFCCCC
for ( i = 1; i != 10; i += 5 ) {
  // ...
}

Compliant Solution

...

Code Block
bgColor#ccccff
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 allto terminate a loop may result in infinite loops and denial of service.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MSC36-J

low

unlikely

low

P1

L3

...