Skip to content

Commit 0e785e4

Browse files
committed
charLiteralWithCharPtrCompare: Improved warning to catch any char literal
1 parent e417e15 commit 0e785e4

2 files changed

Lines changed: 6 additions & 3 deletions

File tree

lib/checkstring.cpp

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ void CheckString::checkSuspiciousStringCompare()
168168
continue;
169169
if (varTok->tokType() == Token::eString || varTok->tokType() == Token::eNumber)
170170
std::swap(varTok, litTok);
171-
else if (litTok->tokType() != Token::eString && litTok->tokType() != Token::eNumber)
171+
else if (!Token::Match(litTok, "%char%|%num%|%str%"))
172172
continue;
173173

174174
// Pointer addition?
@@ -200,10 +200,13 @@ void CheckString::checkSuspiciousStringCompare()
200200
varTok = varTok->astParent();
201201
const std::string varname = varTok->expressionString();
202202

203+
const bool ischar(litTok->tokType() == Token::eChar ||
204+
(!litTok->originalName().empty() &&
205+
litTok->originalName().front() == '\''));
203206
if (litTok->tokType() == Token::eString) {
204207
if (_tokenizer->isC() || (var && var->isArrayOrPointer()))
205208
suspiciousStringCompareError(tok, varname);
206-
} else if (litTok->originalName() == "'\\0'" && var && var->isPointer()) {
209+
} else if (ischar && var && var->isPointer()) {
207210
suspiciousStringCompareError_char(tok, varname);
208211
}
209212
}

test/teststring.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ class TestString : public TestFixture {
367367

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

0 commit comments

Comments
 (0)