Skip to content

Commit bec10bb

Browse files
committed
Fix FP arrayIndexOutOfBounds for a for loop whose condition changes in its body
1 parent bcee906 commit bec10bb

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

‎lib/valueflow.cpp‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5299,7 +5299,11 @@ static bool valueFlowForLoop2(const Token *tok,
52995299

53005300
memory1.swap(startMemory);
53015301
if (!error) {
5302-
memory2.swap(endMemory);
5302+
// When the limit of iterations was reached because only the loop body changes the condition,
5303+
// the last iteration is not known either
5304+
const Token* bodyStart = tok->linkAt(1)->next();
5305+
if (result == 0 || !findExpressionChanged(secondExpression, bodyStart, bodyStart->link(), settings))
5306+
memory2.swap(endMemory);
53035307
// The state after the loop is only known when the condition became false. When the limit of
53045308
// iterations was reached the loop runs on, or exits later in a state that is not known.
53055309
if (result == 0)

‎test/testbufferoverrun.cpp‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2708,6 +2708,19 @@ class TestBufferOverrun : public TestFixture {
27082708
" }\n"
27092709
"}\n");
27102710
ASSERT_EQUALS("[test.cpp:4:14]: (error) Array 'a[10]' accessed at index 9998, which is out of bounds. [arrayIndexOutOfBounds]\n", errout_str());
2711+
2712+
check("int f() {\n"
2713+
" const char s[] = \"abc\";\n"
2714+
" int n = 0;\n"
2715+
" for (int i = 0, done = 0; done == 0; i++) {\n"
2716+
" if (s[i] == '\\0')\n"
2717+
" done = 1;\n"
2718+
" else\n"
2719+
" n++;\n"
2720+
" }\n"
2721+
" return n;\n"
2722+
"}\n");
2723+
ASSERT_EQUALS("", errout_str());
27112724
}
27122725

27132726
void array_index_for_neq() {

0 commit comments

Comments
 (0)