メインコンテンツ

CWE Rule 835

Loop with Unreachable Exit Condition

Since R2026a

Description

Loop with Unreachable Exit Condition

Polyspace Implementation

The rule checker checks for Infinite loop.

Examples

expand all

Issue

This issue occurs when a loop termination condition is never satisfied after the loop is entered. This can happen due to improper validation or update of loop variables, or if external factors prevent the loop from reaching its terminating state.

Polyspace does not report a violation on 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, these programming errors can lead to unintended infinite loops:

  • 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 code that updates the loop index is reachable and that 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.

Example — Loop Index Not Updated

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).

void cleanArray(int* fullArray, int* finalArray, int lenFullArray, int lenfinalArray) {
    int i,j;
    for(i = 0, j = 0; i < lenFullArray; j++) {  // Noncompliant
        if(fullArray[i] >= 0 && j < lenfinalArray) {
            finalArray[j] = fullArray[i];
            j++;
        }
    }
}
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++) {    // Compliant
        if(fullArray[i] >= 0 && j < lenfinalArray) {  
            finalArray[j] = fullArray[i];
            j++;
        }
    }
}

Check Information

Category: Behavioral Problems
PQL Name: std.cwe_native.R835

Version History

Introduced in R2026a