diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index c8c029aa708..e9697a6f7f1 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -5299,7 +5299,11 @@ static bool valueFlowForLoop2(const Token *tok, memory1.swap(startMemory); if (!error) { - memory2.swap(endMemory); + // 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)) + memory2.swap(endMemory); // The state after the loop is only known when the condition became false. When the limit of // iterations was reached the loop runs on, or exits later in a state that is not known. if (result == 0) diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index e667c87645d..74e59813b15 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -2708,6 +2708,29 @@ class TestBufferOverrun : public TestFixture { " }\n" "}\n"); ASSERT_EQUALS("[test.cpp:4:14]: (error) Array 'a[10]' accessed at index 9998, which is out of bounds. [arrayIndexOutOfBounds]\n", errout_str()); + + check("int f() {\n" + " const char s[] = \"abc\";\n" + " int n = 0;\n" + " for (int i = 0, done = 0; done == 0; i++) {\n" + " if (s[i] == '\\0')\n" + " done = 1;\n" + " else\n" + " n++;\n" + " }\n" + " return n;\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("void f() {\n" + " int a[10];\n" + " for (int i = 0, done = 0; done == 0; i++) {\n" + " a[i] = 0;\n" + " if (i == 9)\n" + " done = 1;\n" + " }\n" + "}\n"); + TODO_ASSERT_EQUALS("", "[test.cpp:5:15] -> [test.cpp: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]\n", errout_str()); } void array_index_for_neq() {