Skip to content

Commit a2db005

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 68bf94a commit a2db005

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
@@ -165,6 +165,7 @@ class TestBufferOverrun : public TestFixture {
165165
TEST_CASE(array_index_75);
166166
TEST_CASE(array_index_76);
167167
TEST_CASE(array_index_77);
168+
TEST_CASE(array_index_78); // #14992, #14989
168169
TEST_CASE(array_index_multidim);
169170
TEST_CASE(array_index_switch_in_for);
170171
TEST_CASE(array_index_for_in_for); // FP: #2634
@@ -2031,6 +2032,44 @@ class TestBufferOverrun : public TestFixture {
20312032
errout_str());
20322033
}
20332034

2035+
void array_index_78()
2036+
{
2037+
check("constexpr char arr[] = {'A', 'B', 'C', 'D'};\n" // #14992
2038+
"int f() {\n"
2039+
" if constexpr (4 < sizeof(arr) / sizeof(arr[0])) {\n"
2040+
" return arr[4];\n"
2041+
" } else {\n"
2042+
" return -1;\n"
2043+
" }\n"
2044+
"}\n");
2045+
ASSERT_EQUALS("", errout_str());
2046+
2047+
check("constexpr char arr[] = {'A', 'B', 'C', 'D'};\n"
2048+
"int f() {\n"
2049+
" if constexpr (4 == sizeof(arr) / sizeof(arr[0])) {\n"
2050+
" return arr[4];\n"
2051+
" } else {\n"
2052+
" return -1;\n"
2053+
" }\n"
2054+
"}\n");
2055+
ASSERT_EQUALS("[test.cpp:4:19]: (error) Array 'arr[4]' accessed at index 4, which is out of bounds. [arrayIndexOutOfBounds]\n", errout_str());
2056+
2057+
check("struct S {\n" // #14989
2058+
" int a[10];\n"
2059+
"};\n"
2060+
"template <int N>\n"
2061+
"int g(const S& x) {\n"
2062+
" if (N == 7)\n"
2063+
" return x.a[N];\n"
2064+
" else\n"
2065+
" return x.a[N - 17];\n"
2066+
"}\n"
2067+
"int f(const S& x) {\n"
2068+
" return g<7>(x);\n"
2069+
"}\n");
2070+
ASSERT_EQUALS("", errout_str());
2071+
}
2072+
20342073
void array_index_multidim() {
20352074
check("void f()\n"
20362075
"{\n"

0 commit comments

Comments
 (0)