From bec10bb3318d5742b3a6a304af165ecfb683bef1 Mon Sep 17 00:00:00 2001 From: APX403 Date: Sat, 28 Nov 2026 16:20:24 +0200 Subject: [PATCH] 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() {