Skip to content

Commit fd0f2d7

Browse files
committed
Fixed cppcheck-opensource#4929 (False positive: possible null pointer deref (checks dont handle && and || well))
1 parent b15eeb0 commit fd0f2d7

2 files changed

Lines changed: 25 additions & 5 deletions

File tree

lib/checknullpointer.cpp

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -580,8 +580,8 @@ void CheckNullPointer::nullPointerStructByDeRefAndChec()
580580
tok1 = tok1->next();
581581
skipvar.insert(tok1->varId());
582582
continue;
583-
} else if (Token::Match(tok1, "( ! %var% %oror%") ||
584-
Token::Match(tok1, "( %var% &&")) {
583+
} else if (Token::Match(tok1, "(|%oror% ! %var% %oror%") ||
584+
Token::Match(tok1, "(|&& %var% &&")) {
585585
// TODO: there are false negatives caused by this. The
586586
// variable should be removed from skipvar after the
587587
// condition
@@ -631,6 +631,8 @@ void CheckNullPointer::nullPointerStructByDeRefAndChec()
631631
const unsigned int varid1(tok1->varId());
632632
if (varid1 == 0)
633633
continue;
634+
if (skipvar.find(varid1) != skipvar.end())
635+
continue;
634636
const Token *tok2 = tok1->previous();
635637
while (tok2 && !Token::Match(tok2, "[;{}]")) {
636638
if (Token::Match(tok2, "%varid% =", varid1)) {
@@ -850,7 +852,7 @@ void CheckNullPointer::nullPointerByDeRefAndChec()
850852
// Don't write warning if the dereferencing is
851853
// guarded by ?: or &&
852854
const Token *tok2 = tok1->previous();
853-
if (tok2 && (tok2->isArithmeticalOp() || tok2->str() == "(")) {
855+
if (tok2 && (tok2->isArithmeticalOp() || Token::Match(tok2, "[(,]"))) {
854856
while (tok2 && !Token::Match(tok2, "[;{}?:]")) {
855857
if (tok2->str() == ")") {
856858
tok2 = tok2->link();
@@ -859,8 +861,8 @@ void CheckNullPointer::nullPointerByDeRefAndChec()
859861
break;
860862
}
861863
}
862-
// guarded by &&
863-
if (tok2->varId() == varid && tok2->next()->str() == "&&")
864+
// guarded by && or ||
865+
if (Token::Match(tok2, "%varid% &&|%oror%",varid))
864866
break;
865867
tok2 = tok2->previous();
866868
}

test/testnullpointer.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,24 @@ class TestNullPointer : public TestFixture {
468468
"}");
469469
ASSERT_EQUALS("", errout.str());
470470

471+
check("void f(ABC *abc) {\n"
472+
" x(def || !abc || y(def, abc->a));\n"
473+
" if (abc) {}\n"
474+
"}");
475+
ASSERT_EQUALS("", errout.str());
476+
477+
check("void f(ABC *abc) {\n"
478+
" x(abc && y(def, abc->a));\n"
479+
" if (abc) {}\n"
480+
"}");
481+
ASSERT_EQUALS("", errout.str());
482+
483+
check("void f(ABC *abc) {\n"
484+
" x(def && abc && y(def, abc->a));\n"
485+
" if (abc) {}\n"
486+
"}");
487+
ASSERT_EQUALS("", errout.str());
488+
471489
// #3228 - calling function with null object
472490
{
473491
const char code[] = "void f(Fred *fred) {\n"

0 commit comments

Comments
 (0)