MCPcopy Create free account
hub / github.com/cppcheck-opensource/cppcheck / checkSuspiciousStringCompare

Method checkSuspiciousStringCompare

lib/checkstring.cpp:161–198  ·  view source on GitHub ↗

----------------------------------------------------------------------------- Detect "str == '\0'" where "*str == '\0'" is correct. Comparing char* with each other instead of using strcmp() -----------------------------------------------------------------------------

Source from the content-addressed store, hash-verified

159// Comparing char* with each other instead of using strcmp()
160//-----------------------------------------------------------------------------
161void CheckStringImpl::checkSuspiciousStringCompare()
162{
163 if (!mSettings.severity.isEnabled(Severity::warning))
164 return;
165
166 logChecker("CheckString::checkSuspiciousStringCompare"); // warning
167
168 const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
169 for (const Scope * scope : symbolDatabase->functionScopes) {
170 for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
171 if (!tok->isComparisonOp())
172 continue;
173
174 const Token* varTok = tok->astOperand1();
175 const Token* litTok = tok->astOperand2();
176 if (!varTok || !litTok) // <- failed to create AST for comparison
177 continue;
178 if (Token::Match(varTok, "%char%|%num%|%str%"))
179 std::swap(varTok, litTok);
180 else if (!Token::Match(litTok, "%char%|%num%|%str%"))
181 continue;
182
183 if (varTok->isLiteral())
184 continue;
185
186 const ValueType* varType = varTok->valueType();
187 if (varTok->isCpp() && (!varType || !varType->isIntegral()))
188 continue;
189
190 if (litTok->tokType() == Token::eString) {
191 if (varTok->isC() || (varType && varType->pointer))
192 suspiciousStringCompareError(tok, varTok->expressionString(), litTok->isLong());
193 } else if (litTok->tokType() == Token::eChar && varType && varType->pointer) {
194 suspiciousStringCompareError_char(tok, varTok->expressionString());
195 }
196 }
197 }
198}
199
200void CheckStringImpl::suspiciousStringCompareError(const Token* tok, const std::string& var, bool isLong)
201{

Callers 1

runChecksMethod · 0.80

Calls 8

nextMethod · 0.80
astOperand1Method · 0.80
astOperand2Method · 0.80
isIntegralMethod · 0.80
isCMethod · 0.80
swapFunction · 0.70
isEnabledMethod · 0.45
expressionStringMethod · 0.45

Tested by

no test coverage detected