diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index e908f5bda..a6676579a 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -3159,6 +3159,26 @@ void Tokenizer::simplifyDoublePlusAndDoubleMinus() void Tokenizer::arraySize() { + auto getStrTok = [](Token* tok, bool addLength, Token** endStmt) -> Token* { + if (addLength) { + *endStmt = tok->tokAt(6); + return tok->tokAt(4); + } + if (Token::Match(tok, "%var% [ ] =")) { + tok = tok->tokAt(4); + int parCount = 0; + while (Token::simpleMatch(tok, "(")) { + ++parCount; + tok = tok->next(); + } + if (Token::Match(tok, "%str%")) { + *endStmt = tok->tokAt(parCount + 1); + return tok; + } + } + return nullptr; + }; + for (Token *tok = list.front(); tok; tok = tok->next()) { if (!tok->isName() || !Token::Match(tok, "%var% [ ] =")) continue; @@ -3170,11 +3190,11 @@ void Tokenizer::arraySize() addlength = true; } - if (addlength || Token::Match(tok, "%var% [ ] = %str% ;")) { - tok = tok->next(); - const int sz = Token::getStrArraySize(tok->tokAt(3)); - tok->insertToken(MathLib::toString(sz)); - tok = tok->tokAt(5); + Token* endStmt{}; + if (const Token* strTok = getStrTok(tok, addlength, &endStmt)) { + const int sz = Token::getStrArraySize(strTok); + tok->next()->insertToken(MathLib::toString(sz)); + tok = endStmt; } else if (Token::Match(tok, "%var% [ ] = {")) { diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index 50b390961..23d27d03f 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -194,6 +194,7 @@ private: TEST_CASE(array_index_67); // #1596 TEST_CASE(array_index_68); // #6655 TEST_CASE(array_index_69); // #6370 + TEST_CASE(array_index_70); // #11355 TEST_CASE(array_index_multidim); TEST_CASE(array_index_switch_in_for); TEST_CASE(array_index_for_in_for); // FP: #2634 @@ -1901,6 +1902,15 @@ private: ASSERT_EQUALS("[test.cpp:5]: (error) Array 'a[4]' accessed at index 30, which is out of bounds.\n", errout.str()); } + // #11355 + void array_index_70() { + check("void f() {\n" + " static const char a[] = ((\"test\"));\n" + " printf(\"%c\", a[5]);\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:3]: (error) Array 'a[5]' accessed at index 5, which is out of bounds.\n", errout.str()); + } + void array_index_multidim() { check("void f()\n" "{\n"