diff --git a/lib/checkbufferoverrun.cpp b/lib/checkbufferoverrun.cpp index bddf1fdb2..cbce6bb60 100644 --- a/lib/checkbufferoverrun.cpp +++ b/lib/checkbufferoverrun.cpp @@ -1596,15 +1596,15 @@ void CheckBufferOverrun::negativeIndex() const long index = MathLib::toLongNumber(tok->next()->str()); if (index < 0) { - // Multidimensional index => error - if (Token::simpleMatch(tok->previous(), "]") || Token::simpleMatch(tok->tokAt(3), "[")) - negativeIndexError(tok, index); + // Negative index. Check if it's an array. + const Token *tok2 = tok; + while (Token::simpleMatch(tok2->previous(), "]")) + tok2 = tok2->previous()->link(); - // 1-dimensional array => error - else if (tok->previous() && tok->previous()->varId()) + if (tok2->previous() && tok2->previous()->varId()) { - const Token *tok2 = Token::findmatch(_tokenizer->tokens(), "%varid%", tok->previous()->varId()); - if (tok2 && Token::Match(tok2->next(), "[ %any% ] ;")) + const Token *tok3 = Token::findmatch(_tokenizer->tokens(), "%varid%", tok2->previous()->varId()); + if (tok3 && Token::Match(tok3->next(), "[ %any% ] ;|[")) negativeIndexError(tok, index); } } diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index 6a1cb8522..b175e254c 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -1155,6 +1155,13 @@ private: " if (p[-1]);\n" "}\n"); ASSERT_EQUALS("", errout.str()); + + // ticket #1850 + check("int f(const std::map > &m)\n" + "{\n" + " return m[0][-1];\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); } void array_index_for_decr()