diff --git a/lib/checkbufferoverrun.cpp b/lib/checkbufferoverrun.cpp index 07294cadc..e798df48b 100644 --- a/lib/checkbufferoverrun.cpp +++ b/lib/checkbufferoverrun.cpp @@ -1439,11 +1439,10 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable() // check string literals for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { if (Token::Match(tok, "%str% [ %num% ]")) { - std::string str = tok->strValue(); - std::size_t index = (std::size_t)std::atoi(tok->strAt(2).c_str()); - if (index > str.length()) { + const std::size_t strLen = tok->str().size() - 2; // Don't count enclosing quotes + const std::size_t index = (std::size_t)std::atoi(tok->strAt(2).c_str()); + if (index > strLen) bufferOverrunError(tok, tok->str()); - } } } diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index 6a1320c47..dc560c020 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -169,6 +169,7 @@ private: TEST_CASE(buffer_overrun_25); // #4096 TEST_CASE(buffer_overrun_26); // #4432 (segmentation fault) TEST_CASE(buffer_overrun_27); // #4444 (segmentation fault) + TEST_CASE(buffer_overrun_28); // Out of bound char array access TEST_CASE(buffer_overrun_bailoutIfSwitch); // ticket #2378 : bailoutIfSwitch TEST_CASE(buffer_overrun_function_array_argument); TEST_CASE(possible_buffer_overrun_1); // #3035 @@ -2719,6 +2720,11 @@ private: ASSERT_EQUALS("", errout.str()); } + void buffer_overrun_28() { + check("char c = \"abc\"[4];"); + ASSERT_EQUALS("[test.cpp:1]: (error) Buffer is accessed out of bounds: \"abc\"\n", errout.str()); + } + void buffer_overrun_bailoutIfSwitch() { // No false positive check("void f1(char *s) {\n"