Loop with unreachable exit condition¶
ID: java/unreachable-exit-in-loopKind: problemSecurity severity: 7.5Severity: warningPrecision: mediumTags: - security - external/cwe/cwe-835Query suites: - java-security-extended.qls - java-security-and-quality.qls
Click to see the query in the CodeQL repository
Loops can contain multiple exit conditions, either directly in the loop condition or as guards aroundbreak orreturn statements. If an exit condition cannot be satisfied, then the code is misleading at best, and the loop might not terminate.
Recommendation¶
When writing a loop that is intended to terminate, make sure that all the necessary exit conditions can be satisfied and that loop termination is clear.
Example¶
The following example shows a potentially infinite loop, since the inner loop condition is constantly true. Of course, the loop may or may not be infinite depending on the behavior ofshouldBreak, but if this was intended as the only exit condition the loop should be rewritten to make this clear.
for(inti=0;i<10;i++){for(intj=0;i<10;j++){// BAD: Potential infinite loop: i should be j// do stuffif(shouldBreak())break;}}
To fix the loop the condition is corrected to check the right variable.
for(inti=0;i<10;i++){for(intj=0;j<10;j++){// GOOD: correct variable j// do stuffif(shouldBreak())break;}}
References¶
Java Language Specification:Blocks and Statements.
Common Weakness Enumeration:CWE-835.