diff --git a/lib/programmemory.cpp b/lib/programmemory.cpp index 9905bb074..5963c8313 100644 --- a/lib/programmemory.cpp +++ b/lib/programmemory.cpp @@ -249,17 +249,28 @@ static void fillProgramMemoryFromAssignments(ProgramMemory& pm, const Token* tok if (indentlevel <= 0) break; --indentlevel; + if (Token::simpleMatch(tok2->previous(), "else {")) + tok2 = tok2->linkAt(-2)->previous(); } if (tok2->str() == "}") { - const Token *cond = tok2->link(); - cond = Token::simpleMatch(cond->previous(), ") {") ? cond->linkAt(-1) : nullptr; - if (cond && conditionIsFalse(cond->astOperand2(), state)) - tok2 = cond->previous(); - else if (cond && conditionIsTrue(cond->astOperand2(), state)) { - ++indentlevel; - continue; - } else - break; + const Token *cond = getCondTokFromEnd(tok2); + const bool inElse = Token::simpleMatch(tok2->link()->previous(), "else {"); + if (cond) { + if (conditionIsFalse(cond, state)) { + if (inElse) { + ++indentlevel; + continue; + } + tok2 = cond->astParent()->previous(); + } + else if (conditionIsTrue(cond, state)) { + if (inElse) + tok2 = tok2->link()->tokAt(-2); + ++indentlevel; + continue; + } + } + break; } } } diff --git a/test/testnullpointer.cpp b/test/testnullpointer.cpp index 3ad9692b7..3be51772f 100644 --- a/test/testnullpointer.cpp +++ b/test/testnullpointer.cpp @@ -112,6 +112,7 @@ private: TEST_CASE(nullpointer69); // #8143 TEST_CASE(nullpointer70); TEST_CASE(nullpointer71); // #10178 + TEST_CASE(nullpointer72); // #10321 TEST_CASE(nullpointer_addressOf); // address of TEST_CASE(nullpointerSwitch); // #2626 TEST_CASE(nullpointer_cast); // #4692 @@ -2239,6 +2240,34 @@ private: ASSERT_EQUALS("", errout.str()); } + void nullpointer72() { + check("void f(bool flag2, int* ptr) {\n" + " bool flag1 = true;\n" + " if (flag2) {\n" + " if (ptr != nullptr)\n" + " (*ptr)++;\n" + " else\n" + " flag1 = false;\n" + " }\n" + " if (flag1 && flag2)\n" + " (*ptr)++;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + + check("void f(bool flag2, int* ptr) {\n" + " bool flag1 = true;\n" + " if (flag2) {\n" + " if (ptr != nullptr)\n" + " (*ptr)++;\n" + " else\n" + " flag1 = false;\n" + " }\n" + " if (!flag1 && flag2)\n" + " (*ptr)++;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4] -> [test.cpp:10]: (warning) Either the condition 'ptr!=nullptr' is redundant or there is possible null pointer dereference: ptr.\n", errout.str()); + } + void nullpointer_addressOf() { // address of check("void f() {\n" " struct X *x = 0;\n"