Main Content

Infinite loop

Loop termination condition might never be satisfied

Since R2023a

Description

This defect occurs when a loop termination condition is never satisfied after the loop is entered.

The checker skips intentional infinite loops such as while(1). Code following intentional infinite loops are flagged by the Unreachable code checker.

Risk

Unintended infinite loops often indicate an error in the program logic. For instance, one of the following programming errors might have occurred:

  • The loop index is never updated inside the loop.

  • The loop index is updated in branches inside the loop that are unreachable.

  • The loop index is updated in a way that the index never satisfies the loop termination condition.

Fix

Fix the programming error if any. Make sure that the loop index update is reachable, and the loop index eventually acquires a value that makes the loop terminate.

If you determine that the loop termination condition is satisfied under certain circumstances (false positive), add comments to your result or code to avoid another review. See

Examples

expand all

void cleanArray(int* fullArray, int* finalArray, int lenFullArray, int lenfinalArray) {
    int i,j;
    for(i = 0, j = 0; i < lenFullArray; j++) {
        if(fullArray[i] >= 0 && j < lenfinalArray) {
            finalArray[j] = fullArray[i];
            j++;
        }
    }
}

In this example, the loop uses two indices to cycle through two arrays. The index used in the loop termination condition is never updated inside the loop, possibly because of a programming error (the other index is updated twice).

Correction – Update Loop Index

Make sure to update the loop index used in the loop termination condition.

void cleanArray(int* fullArray, int* finalArray, int lenFullArray, int lenfinalArray) {
    int i,j;
    for(i = 0, j = 0; i < lenFullArray; i++) {
        if(fullArray[i] >= 0 && j < lenfinalArray) {
            finalArray[j] = fullArray[i];
            j++;
        }
    }
}
#include <stdint.h>

uint32_t idx;

void func(void);

void foo() {
    while(idx) {
        func();
    }
}

In this example, the variable idx is seemingly not updated in the while loop, leading to the detection of an infinite loop.

The issue happens because the definition of the function func() is not available to the Bug Finder analysis. Therefore, the analysis stubs the function and assumes that the function does not update global variables, including the variable idx.

Result Information

Group: Data flow
Language: C | C++
Default: On
Command-Line Syntax: INFINITE_LOOP
Impact: High

Version History

Introduced in R2023a