INFINITE_LOOP.LOCAL

Infinite loop with local variable

The INFINITE_LOOP checkers find instances of loops that have no exit. The checkers track the variables that control loop exit, flagging a defect if the conditions are invariant. When the validity of a condition doesn't change from one iteration to another, the loop never terminates. The INFINITE_LOOP.LOCAL checker finds infinite loops whose exit conditions are based on a local variable.

Vulnerability and risk

An infinite loop can cause a program to hang up indefinitely or crash, possibly allowing a denial-of-service (DoS) attack due to excessive use of CPU or memory resources.

Vulnerable code example 1

Copy
    void infinite_loop(int a)
      {
        int i=0;
        while (true) {
          if (i >= 10) {
            if (a == 11) { 
              break;
            }
          }
         i++;
       }
     }

Klocwork flags this situation as an infinite loop, since, unless 'a' equals 11 on entry to the loop, it will never reach that value and so the loop will never reach a valid exit condition. In this case, the INFINITE_LOOP.LOCAL checker has found a typical infinite loop whose exit condition is based on a local variable.

Fixed code example 1

Copy
    void infinite_loop(int a)
      {
        int i=0;
        while (true) {
          if (i >= 10) {
            if (a == 11) { 
              break;
            } else {
              a++;
            }
          }
         i++;
       }
     }

In the fixed code example, 'a' is incremented, so that the function has an exit.

Vulnerable code example 2

Copy
    void foo() {
      int i=get();
      int j=1;
      while(1) {
        if (i==1) {
          j++;
        } else {
          break;
        }
      }
    }

In this example, Klocwork flags an INFINITE_LOOP defect because 'i' is never changed. The function has no exit since its exit condition is invariant.

Fixed code example 2

Copy
    void foo() {
      int i=get();
      int j=1;
      while(1) {
        if (i==1) {
          i++;
        } else {
          break;
        }
      }
    }

In the fixed code example, variable 'i' is incremented, changing the exit condition for the function.