From bec10bb3318d5742b3a6a304af165ecfb683bef1 Mon Sep 17 00:00:00 2001 From: APX403 Date: Sat, 28 Nov 2026 16:20:24 +0200 Subject: [PATCH 1/2] Fix FP arrayIndexOutOfBounds for a for loop whose condition changes in its body --- lib/valueflow.cpp | 6 +++++- test/testbufferoverrun.cpp | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) 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..eee6b4056e6 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -2708,6 +2708,19 @@ 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()); } void array_index_for_neq() { From db68cfa3fa1a6fa5c838463a2c77465a1909c631 Mon Sep 17 00:00:00 2001 From: APX403 Date: Thu, 3 Dec 2026 22:04:28 +0200 Subject: [PATCH 2/2] Add a TODO test for a for loop flag set at the last valid index --- test/testbufferoverrun.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index eee6b4056e6..74e59813b15 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -2721,6 +2721,16 @@ class TestBufferOverrun : public TestFixture { " 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() {