Skip to content

Fix FP arrayIndexOutOfBounds for a for loop whose condition changes in its body - #9110

Open
APX403 wants to merge 1 commit into
cppcheck-opensource:mainfrom
APX403:fix-forloop-cond-in-body
Open

APX403 wants to merge 1 commit into
cppcheck-opensource:mainfrom
APX403:fix-forloop-cond-in-body

Conversation

@APX403

@APX403 APX403 commented Dec 3, 2026

Copy link
Copy Markdown

arrayIndexOutOfBounds reports index 9998 for a for loop whose condition only changes in its body:

int f(void) {
    const char s[] = "abc";
    int n = 0;
    for (int i = 0, done = 0; done == 0; i++) {
        if (s[i] == '\0')
            done = 1;
        else
            n++;
    }
    return n;
}
loop.c:5:14: error: Array 's[4]' accessed at index 9998, which is out of bounds. [arrayIndexOutOfBounds]

valueFlowForLoop2() runs the three expressions of the loop header without the body, so done == 0 stays true until maxForLoopCount is reached, and the memory of the last pass is then used as the last iteration, which puts 9998 into i in the body. Since #8899 the state after the loop is not used when the limit is reached; when the body changes the condition, the last iteration is not known either. An endless loop such as for (int n = 0; 1; ++n) still reports index 9998, as the test for ticket 13109 expects.

raylib's raygui.h splits the item texts of GuiToggleGroup() with such a loop (raygui.h#L2189), which showed up in the package run of #9078.

I don't have a Trac account, so I couldn't create a ticket for this.

@dmcppcheck

Copy link
Copy Markdown
Contributor

There should probably be a trac ticket for this PR. Please create it, or ask us to create it. Then the PR title should be updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants