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 — Constant loop condition — CodeQL query help documentation

Constant loop condition¶

ID: java/constant-loop-condition
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - quality
   - reliability
   - correctness
   - external/cwe/cwe-835
Query suites:
   - java-code-quality.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 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.

Object getField(Object obj, String name) throws NoSuchFieldError {
  Class clazz = obj.getClass();
  while (clazz != null) {
    for (Field f : clazz.getDeclaredFields()) {
      if (f.getName().equals(name)) {
        f.setAccessible(true);
        return f.get(obj);
      }
    }
  }
  throw new NoSuchFieldError(name);
}

The solution is to rewrite the code as follows using an if-statement.

Object getField(Object obj, String name) throws NoSuchFieldError {
  Class clazz = obj.getClass();
  if (clazz != null) {
    for (Field f : clazz.getDeclaredFields()) {
      if (f.getName().equals(name)) {
        f.setAccessible(true);
        return f.get(obj);
      }
    }
  }
  throw new NoSuchFieldError(name);
}

References¶

  • Java Language Specification: Blocks and Statements.

  • Common Weakness Enumeration: CWE-835.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — 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.