Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

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

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

APX403 wants to merge 2 commits 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.

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

The change removes the 9998 FP from the example in the description, and the tests pass. Two closely related forms of the same loop still give a false positive:

  1. A flag set at the last valid index: if (i == 9) done = 1; with a[10]. Base reported index 9998. The PR now reports arrayIndexOutOfBoundsCond at index 10, which is still wrong: i == 9 ends the loop, so i never reaches 10. The value 10 already existed in base, where the 9998 error at the same spot hid it.
  2. A flag combined with a bound in the condition: !done && i < 100. The condition becomes false within the iteration limit (result == 0), so the last iteration is still taken from the header only, even though the body changes done. Index 99 is reported for s[4], as in base.

So the reasoning that the last iteration is unknown when the body changes the condition is only applied when the limit is reached. I found no crash, hang or new kind of false positive.

Comments

# Comment By Where Status
1 PR should have a trac ticket and the title should reference it @dmcppcheck general ⚠️ Open
2 Last iteration still taken from the header when the condition ends in time but the body changes it (!done && i < 100) AI review lib/valueflow.cpp:5305 🆕 New
3 Same pattern with the flag set at the last valid index still gives an FP (arrayIndexOutOfBoundsCond index 10) AI review test/testbufferoverrun.cpp:2723 🆕 New

@APX403, please fix, resolve or reply to the open and new comments: #1, #2, #3.

Testing

I built cppcheck and testrunner in pr/ and cppcheck in base/.

./testrunner TestBufferOverrun TestValueFlow TestUninitVar TestNullPointer TestCondition TestOther: 846 tests, 0 failures.

The example in the PR description: base reports index 9998, the PR reports nothing. An endless loop without a flag still reports 9998.

Remaining false positives (/work/{base,pr}/cppcheck -q --enable=warning b.c):

void g1(void) {
    int a[10];
    for (int i = 0, done = 0; done == 0; i++) {
        a[i] = 0;
        if (i == 9) done = 1;
    }
}
int g3(void) {
    const char s[] = "abc";
    int n = 0;
    for (int i = 0, done = 0; !done && i < 100; i++) {
        if (s[i] == '\0') done = 1; else n++;
    }
    return n;
}

base:

b.c:4:10: error: Array 'a[10]' accessed at index 9998, which is out of bounds. [arrayIndexOutOfBounds]
b.c:11:14: error: Array 's[4]' accessed at index 99, which is out of bounds. [arrayIndexOutOfBounds]

pr:

b.c:4:10: warning: Either the condition 'i==9' is redundant or the array 'a[10]' is accessed at index 10, which is out of bounds. [arrayIndexOutOfBoundsCond]
b.c:11:14: error: Array 's[4]' accessed at index 99, which is out of bounds. [arrayIndexOutOfBounds]

In both cases the code is safe:

  • In g1, --debug shows that i has the possible value 10 in base too (i possible {9,10,0,9998}); only 9998 is gone in the PR.
  • In g3, the loop stops at i == 3.

Automated review of bec10bb by Claude. The pull request was built and tested locally.

Comment thread lib/valueflow.cpp
// When the limit of iterations was reached because only the loop body changes the condition,
// the last iteration is not known either
const Token* bodyStart = tok->linkAt(1)->next();
if (result == 0 || !findExpressionChanged(secondExpression, bodyStart, bodyStart->link(), settings))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

The check is skipped when result == 0, but the comment's reasoning applies there too: if the body changes the condition, the loop can end before the header-only simulation does. Example:

const char s[] = "abc";
for (int i = 0, done = 0; !done && i < 100; i++) {
    if (s[i] == '\0') done = 1;
}

This still gives Array 's[4]' accessed at index 99 (same as base). Dropping memory2 whenever findExpressionChanged(secondExpression, ...) is true, whatever result is, would also cover this case. memoryAfter could still be kept when result == 0.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd rather keep memory2 there. With i < 100 in the condition, 99 is the real last iteration whenever the body doesn't set done earlier, while 9998 is only where the simulation stopped. Main reports the same index 99 when this loop is written with break, with done declared before the loop, or as a while loop (as arrayIndexOutOfBoundsCond), so dropping memory2 would only change the form with two variables in the init statement. In that form it would also hide real overruns like this one, which main and this PR report at index 99, just as they do when it is written with break:

int next(void);
void f(void) {
    char line[50];
    for (int i = 0, done = 0; !done && i < 100; i++) {
        line[i] = (char)next();
        if (line[i] == '\n') done = 1;
    }
}

" }\n"
" return n;\n"
"}\n");
ASSERT_EQUALS("", errout_str());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

A variant of the new test is still reported:

void g1(void) {
    int a[10];
    for (int i = 0, done = 0; done == 0; i++) {
        a[i] = 0;
        if (i == 9) done = 1;
    }
}

The PR reports Either the condition 'i==9' is redundant or the array 'a[10]' is accessed at index 10 (base reported index 9998 instead). i == 9 ends the loop, so 10 is never used as an index. The value comes from forwarding i==9 through i++ back into the body, ignoring that done = 1 ends the loop. In base it was hidden behind the 9998 error. Please consider adding this case, at least as a TODO assert.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added as a TODO assert in db68cfa. The 10 comes from i == 9 being forwarded after the if and through i++ into the next iteration, without taking into account that done = 1 ends the loop. Written with break instead of the flag, the loop gives no warning. Fixing it would mean teaching the forward analysis that the loop doesn't go on after done = 1, which I'd keep out of this PR

@dmcppcheck

Copy link
Copy Markdown
Contributor

Test results for commit bec10bb (tools/test-my-pr.py, main compared to this PR):

Test: http://ec2-51-20-36-10.eu-north-1.compute.amazonaws.com/pr-9110/
packages: 1000
Differing warnings: 0 (+0 -0)
Timing: -0.1% (http://ec2-51-20-36-10.eu-north-1.compute.amazonaws.com/pr-9110/2026-12-03_10-49-43-bec10bb3318d_timing.html)

Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong.

@APX403

APX403 commented Dec 5, 2026

Copy link
Copy Markdown
Author

I don't have a Trac account, could you create the ticket for me? I'll update the title once it exists

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