From 480c403511f1a649fe44d40e31360c82d5a0c540 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sun, 2 Oct 2011 19:27:18 +0200 Subject: [PATCH] Fixed #3125 (FP: Possible null pointer dereference in conditional operator) --- lib/checknullpointer.cpp | 17 ++++++++++++++++- test/testnullpointer.cpp | 25 +++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/lib/checknullpointer.cpp b/lib/checknullpointer.cpp index ae97e7d58..acf2f642e 100644 --- a/lib/checknullpointer.cpp +++ b/lib/checknullpointer.cpp @@ -589,8 +589,23 @@ void CheckNullPointer::nullPointerByDeRefAndChec() if (tok1->str() == "break") break; - if (tok1->varId() == varid && !Token::Match(tok1->previous(), "[?:]")) + if (tok1->varId() == varid) { + // Don't write warning if the dereferencing is + // guarded by ?: + const Token *tok2 = tok1->previous(); + if (tok2 && (tok2->isArithmeticalOp() || tok2->str() == "(")) + { + while (tok2 && !Token::Match(tok2, "[;{}?:]")) + { + if (tok2->str() == ")") + tok2 = tok2->link(); + tok2 = tok2->previous(); + } + } + if (Token::Match(tok2, "[?:]")) + continue; + // unknown : this is set by isPointerDeRef if it is // uncertain bool unknown = false; diff --git a/test/testnullpointer.cpp b/test/testnullpointer.cpp index 7e80456e0..9a01034ab 100644 --- a/test/testnullpointer.cpp +++ b/test/testnullpointer.cpp @@ -481,6 +481,31 @@ private: "}\n"); ASSERT_EQUALS("", errout.str()); + check("void foo(int *p)\n" + "{\n" + " int var1 = x ? *p : 5;\n" + " if (!p)\n" + " ;\n" + "}\n"); + TODO_ASSERT_EQUALS("error", "", errout.str()); + + // Ticket #3125 + check("void foo(ABC *p)\n" + "{\n" + " int var1 = p ? (p->a) : 0;\n" + " if (!p)\n" + " ;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + + check("void foo(ABC *p)\n" + "{\n" + " int var1 = p ? (1 + p->a) : 0;\n" + " if (!p)\n" + " ;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + check("void foo(P *p)\n" "{\n" " while (p)\n"