Fixed #2171 (false positive: possible nullpointer dereference)

This commit is contained in:
Daniel Marjamäki 2010-11-04 21:09:32 +01:00
parent 06ec4d9a84
commit f3bf14ba13
2 changed files with 18 additions and 3 deletions

View File

@ -436,14 +436,20 @@ void CheckNullPointer::nullPointerByDeRefAndChec()
void CheckNullPointer::nullPointerByCheckAndDeRef() void CheckNullPointer::nullPointerByCheckAndDeRef()
{ {
// Check if pointer is NULL and then dereference it.. // Check if pointer is NULL and then dereference it..
std::set<unsigned int> pointerVariables;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next())
{ {
if (Token::Match(tok, "if ( ! %var% ) {")) if (Token::Match(tok, "* %var% [;,)=]"))
pointerVariables.insert(tok->next()->varId());
else if (Token::Match(tok, "if ( ! %var% ) {"))
{ {
bool null = true; bool null = true;
const unsigned int varid(tok->tokAt(3)->varId()); const unsigned int varid(tok->tokAt(3)->varId());
if (varid == 0) if (varid == 0)
continue; continue;
if (pointerVariables.find(varid) == pointerVariables.end())
continue;
unsigned int indentlevel = 1; unsigned int indentlevel = 1;
for (const Token *tok2 = tok->tokAt(6); tok2; tok2 = tok2->next()) for (const Token *tok2 = tok->tokAt(6); tok2; tok2 = tok2->next())
{ {

View File

@ -672,20 +672,29 @@ private:
"}\n"); "}\n");
ASSERT_EQUALS("", errout.str()); ASSERT_EQUALS("", errout.str());
check("void foo() {\n" check("void foo(char *p) {\n"
" if (!p) {\n" " if (!p) {\n"
" switch (x) { }\n" " switch (x) { }\n"
" }\n" " }\n"
"}\n"); "}\n");
ASSERT_EQUALS("", errout.str()); ASSERT_EQUALS("", errout.str());
check("void foo(bool p) {\n" check("void foo(char *p) {\n"
" if (!p) {\n" " if (!p) {\n"
" }\n" " }\n"
" return *x;\n" " return *x;\n"
"}\n"); "}\n");
ASSERT_EQUALS("", errout.str()); ASSERT_EQUALS("", errout.str());
// operator!
check("void f() {\n"
" A a;\n"
" if (!a) {\n"
" a.x();\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout.str());
// This is why this check can't be used on the simplified token list // This is why this check can't be used on the simplified token list
check("void f(Foo *foo) {\n" check("void f(Foo *foo) {\n"
" if (!dynamic_cast<bar *>(foo)) {\n" " if (!dynamic_cast<bar *>(foo)) {\n"