From a2db005ea03cbf88f9629743c23667a5f14abd5a Mon Sep 17 00:00:00 2001 From: APX403 Date: Wed, 18 Nov 2026 15:36:44 +0200 Subject: [PATCH] Fix #14992, #14989 FP arrayIndexOutOfBounds and negativeIndex in unreachable branch arrayIndex() checked the indexes of every branch, also of a discarded if constexpr branch and of a branch whose condition is known once the template is instantiated. Skip the unreachable branches with skipUnreachableBranch(), as the other checks that walk all tokens do. --- lib/checkbufferoverrun.cpp | 1 + test/testbufferoverrun.cpp | 39 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/lib/checkbufferoverrun.cpp b/lib/checkbufferoverrun.cpp index c97642b9930..60053f20021 100644 --- a/lib/checkbufferoverrun.cpp +++ b/lib/checkbufferoverrun.cpp @@ -303,6 +303,7 @@ void CheckBufferOverrunImpl::arrayIndex() logChecker("CheckBufferOverrun::arrayIndex"); for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { + tok = skipUnreachableBranch(tok); if (tok->str() != "[") continue; const Token *array = tok->astOperand1(); diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index 0e0bf5ce385..ecb83e87a55 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -165,6 +165,7 @@ class TestBufferOverrun : public TestFixture { TEST_CASE(array_index_75); TEST_CASE(array_index_76); TEST_CASE(array_index_77); + TEST_CASE(array_index_78); // #14992, #14989 TEST_CASE(array_index_multidim); TEST_CASE(array_index_switch_in_for); TEST_CASE(array_index_for_in_for); // FP: #2634 @@ -2031,6 +2032,44 @@ class TestBufferOverrun : public TestFixture { errout_str()); } + void array_index_78() + { + check("constexpr char arr[] = {'A', 'B', 'C', 'D'};\n" // #14992 + "int f() {\n" + " if constexpr (4 < sizeof(arr) / sizeof(arr[0])) {\n" + " return arr[4];\n" + " } else {\n" + " return -1;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("constexpr char arr[] = {'A', 'B', 'C', 'D'};\n" + "int f() {\n" + " if constexpr (4 == sizeof(arr) / sizeof(arr[0])) {\n" + " return arr[4];\n" + " } else {\n" + " return -1;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:19]: (error) Array 'arr[4]' accessed at index 4, which is out of bounds. [arrayIndexOutOfBounds]\n", errout_str()); + + check("struct S {\n" // #14989 + " int a[10];\n" + "};\n" + "template \n" + "int g(const S& x) {\n" + " if (N == 7)\n" + " return x.a[N];\n" + " else\n" + " return x.a[N - 17];\n" + "}\n" + "int f(const S& x) {\n" + " return g<7>(x);\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + } + void array_index_multidim() { check("void f()\n" "{\n"