diff --git a/lib/programmemory.cpp b/lib/programmemory.cpp index 95d977e5f26..aa4bfed3ebd 100644 --- a/lib/programmemory.cpp +++ b/lib/programmemory.cpp @@ -1703,6 +1703,15 @@ namespace { return !values.empty() && values.front().isImpossible(); } + // Is the value of the pointer the address of an object, so that it is not null? + static bool isObjectAddress(const Token* expr, const Values& values) + { + if (!expr->valueType() || expr->valueType()->pointer == 0) + return false; + return values.size() == 1 && values.front().isLifetimeValue() && + values.front().lifetimeKind == ValueFlow::Value::LifetimeKind::Address; + } + // The value of a condition: constraints that exclude zero are true, a value stands for itself static ValueFlow::Value conditionValue(Values values) { @@ -2134,6 +2143,12 @@ namespace { const Values* stored = pm->getValues(expr->exprId()); if (!stored || *stored != *tracked) pm->setValues(expr, *tracked); + // A pointer to an object is true as a bool + if (isObjectAddress(expr, *tracked) && isUsedAsBool(expr, settings)) { + ValueFlow::Value result{1}; + result.setKnown(); + return single(std::move(result)); + } return *tracked; } if (const Values* stored = getStoredValues(expr)) { diff --git a/test/testnullpointer.cpp b/test/testnullpointer.cpp index cecbb27ca09..a7b7fb3c06d 100644 --- a/test/testnullpointer.cpp +++ b/test/testnullpointer.cpp @@ -154,6 +154,7 @@ class TestNullPointer : public TestFixture { TEST_CASE(nullpointer113); // a variable is clamped before the check TEST_CASE(nullpointer114); // the else block changes the value TEST_CASE(nullpointer115); // a range condition overlapping the assumed one + TEST_CASE(nullpointer116); // #14747 TEST_CASE(nullpointer_addressOf); // address of TEST_CASE(nullpointerSwitch); // #2626 TEST_CASE(nullpointer_cast); // #4692 @@ -3375,6 +3376,32 @@ class TestNullPointer : public TestFixture { ASSERT_EQUALS("[test.cpp:4:24]: (warning) Possible null pointer dereference: p [nullPointer]\n", errout_str()); } + void nullpointer116() { // #14747 + check("void f(double *d1, double *d2) {\n" + " if (!d1 && !d2)\n" + " return;\n" + " double d3 = d1 ? *d1 : *d2;\n" + " (void)d3;\n" + "}\n" + "void g() {\n" + " double d = 0;\n" + " f(&d, nullptr);\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("void f(double *d1, double *d2) {\n" + " if (!d1 && !d2)\n" + " return;\n" + " double d3 = d1 ? *d2 : 0;\n" + " (void)d3;\n" + "}\n" + "void g() {\n" + " double d = 0;\n" + " f(&d, nullptr);\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:23]: (warning) Possible null pointer dereference: d2 [nullPointer]\n", errout_str()); + } + void nullpointer_addressOf() { // address of check("void f() {\n" " struct X *x = 0;\n"