charLiteralWithCharPtrCompare: Improved warning to catch any char literal

This commit is contained in:
Daniel Marjamäki 2016-10-09 11:39:20 +02:00
parent e417e15567
commit 0e785e435e
2 changed files with 6 additions and 3 deletions

View File

@ -168,7 +168,7 @@ void CheckString::checkSuspiciousStringCompare()
continue; continue;
if (varTok->tokType() == Token::eString || varTok->tokType() == Token::eNumber) if (varTok->tokType() == Token::eString || varTok->tokType() == Token::eNumber)
std::swap(varTok, litTok); std::swap(varTok, litTok);
else if (litTok->tokType() != Token::eString && litTok->tokType() != Token::eNumber) else if (!Token::Match(litTok, "%char%|%num%|%str%"))
continue; continue;
// Pointer addition? // Pointer addition?
@ -200,10 +200,13 @@ void CheckString::checkSuspiciousStringCompare()
varTok = varTok->astParent(); varTok = varTok->astParent();
const std::string varname = varTok->expressionString(); const std::string varname = varTok->expressionString();
const bool ischar(litTok->tokType() == Token::eChar ||
(!litTok->originalName().empty() &&
litTok->originalName().front() == '\''));
if (litTok->tokType() == Token::eString) { if (litTok->tokType() == Token::eString) {
if (_tokenizer->isC() || (var && var->isArrayOrPointer())) if (_tokenizer->isC() || (var && var->isArrayOrPointer()))
suspiciousStringCompareError(tok, varname); suspiciousStringCompareError(tok, varname);
} else if (litTok->originalName() == "'\\0'" && var && var->isPointer()) { } else if (ischar && var && var->isPointer()) {
suspiciousStringCompareError_char(tok, varname); suspiciousStringCompareError_char(tok, varname);
} }
} }

View File

@ -367,7 +367,7 @@ private:
void suspiciousStringCompare_char() { void suspiciousStringCompare_char() {
check("bool foo(char* c) {\n" check("bool foo(char* c) {\n"
" return c == '\\0';\n" " return c == 'x';\n"
"}"); "}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Char literal compared with pointer 'c'. Did you intend to dereference it?\n", errout.str()); ASSERT_EQUALS("[test.cpp:2]: (warning) Char literal compared with pointer 'c'. Did you intend to dereference it?\n", errout.str());