Constant loop condition¶
ID: java/constant-loop-conditionKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - reliability - correctness - external/cwe/cwe-835Query suites: - 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 none of the exit conditions can ever be satisfied, then the loop will never 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 searches for a field of a given name, and intends to throw an exception if the field cannot be found. However, if the field cannot be found, the double loop structure means that the exit conditions will never be met, resulting in an infinite loop.
ObjectgetField(Objectobj,Stringname)throwsNoSuchFieldError{Classclazz=obj.getClass();while(clazz!=null){for(Fieldf:clazz.getDeclaredFields()){if(f.getName().equals(name)){f.setAccessible(true);returnf.get(obj);}}}thrownewNoSuchFieldError(name);}
The solution is to rewrite the code as follows using anif-statement.
ObjectgetField(Objectobj,Stringname)throwsNoSuchFieldError{Classclazz=obj.getClass();if(clazz!=null){for(Fieldf:clazz.getDeclaredFields()){if(f.getName().equals(name)){f.setAccessible(true);returnf.get(obj);}}}thrownewNoSuchFieldError(name);}
References¶
Java Language Specification:Blocks and Statements.
Common Weakness Enumeration:CWE-835.