Java Reference
In-Depth Information
Noncompliant Code Example
This noncompliant code example initializes the loop counter i to 0 and then increments it
by two on each iteration, basically enumerating all the even, positive values. The loop is
expected to terminate when i is greater than Integer.MAX_VALUE − 1 , an even value. In
this case, the loop fails to terminate because the counter wraps around before becoming
greater than Integer.MAX_VALUE − 1 .
Click here to view code image
for (i = 0; i <= Integer.MAX_VALUE - 1; i += 2) {
// ...
}
Compliant Solution
The loop in this compliant solution terminates when the counter i is greater than In-
teger.MAX_VALUE minus the step value as the loop-terminating condition.
Click here to view code image
for (i = 0; i <= Integer.MAX_VALUE - 2; i += 2) {
// ...
}
Applicability
Incorrect termination of loops may result in infinite loops, poor performance, incorrect
results, and other problems. If any of the conditions used to terminate a loop can be in-
fluenced by an attacker, these errors can be exploited to cause a denial of service or other
attack.
Bibliography
[JLS 2013]
§15.20.1, “Numerical Comparison Operators <, <=, >, and >=”
[Long 2012]
NUM00-J. Detect or prevent integer overflow
Search WWH ::




Custom Search