Fix FN with known condition and sizeof

cppcheck behaved differently if sizeof was to the left or right of the
comparison. In order to fix this, we cannot break the while loop until
all operands have been processed.
This commit is contained in:
Rikard Falkeborn 2020-07-10 23:33:43 +02:00
parent 27841d6b81
commit d8e7e9176b
2 changed files with 7 additions and 3 deletions

View File

@ -1457,6 +1457,7 @@ void CheckCondition::alwaysTrueFalse()
// don't warn when condition checks sizeof result
bool hasSizeof = false;
bool hasNonNumber = false;
tokens.push(tok);
while (!tokens.empty()) {
const Token *tok2 = tokens.top();
@ -1473,9 +1474,9 @@ void CheckCondition::alwaysTrueFalse()
tokens.push(tok2->astOperand1());
tokens.push(tok2->astOperand2());
} else
break;
hasNonNumber = true;
}
if (tokens.empty() && hasSizeof)
if (!hasNonNumber && hasSizeof)
continue;
alwaysTrueFalseError(tok, &tok->values().front());

View File

@ -2987,14 +2987,17 @@ private:
// Avoid FP for sizeof condition
check("void f() {\n"
" if (sizeof(char) != 123) {}\n"
" if (123 != sizeof(char)) {}\n"
"}");
ASSERT_EQUALS("", errout.str());
check("void f() {\n"
" int x = 123;\n"
" if (sizeof(char) != x) {}\n"
" if (x != sizeof(char)) {}\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'sizeof(char)!=x' is always true\n", errout.str());
ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'sizeof(char)!=x' is always true\n"
"[test.cpp:4]: (style) Condition 'x!=sizeof(char)' is always true\n", errout.str());
// Don't warn in assertions. Condition is often 'always true' by intention.
// If platform,defines,etc cause an 'always false' assertion then that is not very dangerous neither