GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Loop with unreachable exit condition — CodeQL query help documentation

Loop with unreachable exit condition¶

ID: java/unreachable-exit-in-loop
Kind: problem
Security severity: 7.5
Severity: warning
Precision: medium
Tags:
   - security
   - external/cwe/cwe-835
Query 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 around break or return 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 of shouldBreak, but if this was intended as the only exit condition the loop should be rewritten to make this clear.

for (int i=0; i<10; i++) {
    for (int j=0; i<10; j++) { // BAD: Potential infinite loop: i should be j
        // do stuff
        if (shouldBreak()) break;
    }
}

To fix the loop the condition is corrected to check the right variable.

for (int i=0; i<10; i++) {
    for (int j=0; j<10; j++) { // GOOD: correct variable j
        // do stuff
        if (shouldBreak()) break;
    }
}

References¶

  • Java Language Specification: Blocks and Statements.

  • Common Weakness Enumeration: CWE-835.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.