Skip to content

Commit e3ce93c

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 6a4fedd commit e3ce93c

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
@@ -168,6 +168,7 @@ class TestBufferOverrun : public TestFixture {
168168
TEST_CASE(array_index_78);
169169
TEST_CASE(array_index_79); // #15225
170170
TEST_CASE(array_index_80);
171+
TEST_CASE(array_index_81); // #14992, #14989
171172
TEST_CASE(array_index_multidim);
172173
TEST_CASE(array_index_switch_in_for);
173174
TEST_CASE(array_index_for_in_for); // FP: #2634
@@ -2128,6 +2129,44 @@ class TestBufferOverrun : public TestFixture {
21282129
ASSERT_EQUALS("", errout_str());
21292130
}
21302131

2132+
void array_index_81()
2133+
{
2134+
check("constexpr char arr[] = {'A', 'B', 'C', 'D'};\n" // #14992
2135+
"int f() {\n"
2136+
" if constexpr (4 < sizeof(arr) / sizeof(arr[0])) {\n"
2137+
" return arr[4];\n"
2138+
" } else {\n"
2139+
" return -1;\n"
2140+
" }\n"
2141+
"}\n");
2142+
ASSERT_EQUALS("", errout_str());
2143+
2144+
check("constexpr char arr[] = {'A', 'B', 'C', 'D'};\n"
2145+
"int f() {\n"
2146+
" if constexpr (4 == sizeof(arr) / sizeof(arr[0])) {\n"
2147+
" return arr[4];\n"
2148+
" } else {\n"
2149+
" return -1;\n"
2150+
" }\n"
2151+
"}\n");
2152+
ASSERT_EQUALS("[test.cpp:4:19]: (error) Array 'arr[4]' accessed at index 4, which is out of bounds. [arrayIndexOutOfBounds]\n", errout_str());
2153+
2154+
check("struct S {\n" // #14989
2155+
" int a[10];\n"
2156+
"};\n"
2157+
"template <int N>\n"
2158+
"int g(const S& x) {\n"
2159+
" if (N == 7)\n"
2160+
" return x.a[N];\n"
2161+
" else\n"
2162+
" return x.a[N - 17];\n"
2163+
"}\n"
2164+
"int f(const S& x) {\n"
2165+
" return g<7>(x);\n"
2166+
"}\n");
2167+
ASSERT_EQUALS("", errout_str());
2168+
}
2169+
21312170
void array_index_multidim() {
21322171
check("void f()\n"
21332172
"{\n"

0 commit comments

Comments
 (0)