Skip to content

Commit

Permalink
Fix FP incorrectStringBooleanError with unknown macro (danmar#5364)
Browse files Browse the repository at this point in the history
  • Loading branch information
chrchr-github committed Aug 23, 2023
1 parent 8cd6194 commit 5a7c7b9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
19 changes: 17 additions & 2 deletions lib/checkstring.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,21 @@ void CheckString::strPlusCharError(const Token *tok)
reportError(tok, Severity::error, "strPlusChar", "Unusual pointer arithmetic. A value of type '" + charType +"' is added to a string literal.", CWE665, Certainty::normal);
}

static bool isMacroUsage(const Token* tok)
{
if (const Token* parent = tok->astParent()) {
if (parent->isExpandedMacro())
return true;
if (parent->isUnaryOp("!")) {
int argn{};
const Token* ftok = getTokenArgumentFunction(parent, argn);
if (ftok && !ftok->function())
return true;
}
}
return false;
}

//---------------------------------------------------------------------------
// Implicit casts of string literals to bool
// Comparing string literal with strlen() with wrong length
Expand Down Expand Up @@ -289,8 +304,8 @@ void CheckString::checkIncorrectStringCompare()
}
}
} else if (Token::Match(tok, "%str%|%char%") &&
!(tok->astParent() && tok->astParent()->isExpandedMacro()) &&
isUsedAsBool(tok))
isUsedAsBool(tok) &&
!isMacroUsage(tok))
incorrectStringBooleanError(tok, tok->str());
}
}
Expand Down
7 changes: 7 additions & 0 deletions test/teststring.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,13 @@ class TestString : public TestFixture {
" ERROR(\"abc\")\n"
"}\n");
ASSERT_EQUALS("", errout.str());

check("void g(int, bool);\n"
"void f() {\n"
" MyAssert(!\"abc\");\n"
" g(2, !\"def\");\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (warning) Conversion of string literal \"def\" to bool always evaluates to true.\n", errout.str());
}

void deadStrcmp() {
Expand Down

0 comments on commit 5a7c7b9

Please sign in to comment.