Skip to content

Commit 109da64

Browse files
committed
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.
1 parent 4ccfcc6 commit 109da64

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

‎lib/checkbufferoverrun.cpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,7 @@ void CheckBufferOverrunImpl::arrayIndex()
303303
logChecker("CheckBufferOverrun::arrayIndex");
304304

305305
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
306+
tok = skipUnreachableBranch(tok);
306307
if (tok->str() != "[")
307308
continue;
308309
const Token *array = tok->astOperand1();

‎test/testbufferoverrun.cpp‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@ class TestBufferOverrun : public TestFixture {
166166
TEST_CASE(array_index_76);
167167
TEST_CASE(array_index_77);
168168
TEST_CASE(array_index_78);
169+
TEST_CASE(array_index_80); // #14992, #14989
169170
TEST_CASE(array_index_multidim);
170171
TEST_CASE(array_index_switch_in_for);
171172
TEST_CASE(array_index_for_in_for); // FP: #2634
@@ -2048,6 +2049,44 @@ class TestBufferOverrun : public TestFixture {
20482049
ASSERT_EQUALS("", errout_str());
20492050
}
20502051

2052+
void array_index_80()
2053+
{
2054+
check("constexpr char arr[] = {'A', 'B', 'C', 'D'};\n" // #14992
2055+
"int f() {\n"
2056+
" if constexpr (4 < sizeof(arr) / sizeof(arr[0])) {\n"
2057+
" return arr[4];\n"
2058+
" } else {\n"
2059+
" return -1;\n"
2060+
" }\n"
2061+
"}\n");
2062+
ASSERT_EQUALS("", errout_str());
2063+
2064+
check("constexpr char arr[] = {'A', 'B', 'C', 'D'};\n"
2065+
"int f() {\n"
2066+
" if constexpr (4 == sizeof(arr) / sizeof(arr[0])) {\n"
2067+
" return arr[4];\n"
2068+
" } else {\n"
2069+
" return -1;\n"
2070+
" }\n"
2071+
"}\n");
2072+
ASSERT_EQUALS("[test.cpp:4:19]: (error) Array 'arr[4]' accessed at index 4, which is out of bounds. [arrayIndexOutOfBounds]\n", errout_str());
2073+
2074+
check("struct S {\n" // #14989
2075+
" int a[10];\n"
2076+
"};\n"
2077+
"template <int N>\n"
2078+
"int g(const S& x) {\n"
2079+
" if (N == 7)\n"
2080+
" return x.a[N];\n"
2081+
" else\n"
2082+
" return x.a[N - 17];\n"
2083+
"}\n"
2084+
"int f(const S& x) {\n"
2085+
" return g<7>(x);\n"
2086+
"}\n");
2087+
ASSERT_EQUALS("", errout_str());
2088+
}
2089+
20512090
void array_index_multidim() {
20522091
check("void f()\n"
20532092
"{\n"

0 commit comments

Comments
 (0)