improving checkSizeofForStrncmpSize

This commit is contained in:
PKEuS 2011-12-23 18:11:34 +01:00 committed by Daniel Marjamäki
parent e9d697b636
commit 8213a15b2a
2 changed files with 24 additions and 11 deletions

View File

@ -433,8 +433,9 @@ void CheckOther::sizeofForArrayParameterError(const Token *tok)
void CheckOther::checkSizeofForStrncmpSize()
{
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase();
const char pattern1[] = "strncmp ( %any% , %any% , sizeof ( %var% ) )";
const char pattern2[] = "strncmp ( %any% , %any% , sizeof %var% )";
static const char pattern0[] = "strncmp (";
static const char pattern1[] = "sizeof ( %var% ) )";
static const char pattern2[] = "sizeof %var% )";
// danmar : this is inconclusive in case the size parameter is
// sizeof(char *) by intention.
@ -442,20 +443,26 @@ void CheckOther::checkSizeofForStrncmpSize()
return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, pattern1) || Token::Match(tok, pattern2)) {
unsigned short tokIdx = 7;
if (tok->strAt(tokIdx) == "(")
++tokIdx;
const Token *tokVar = tok->tokAt(tokIdx);
if (Token::Match(tok, pattern0)) {
const Token *tokVar = tok->tokAt(2);
if (tokVar)
tokVar = tokVar->nextArgument();
if (tokVar)
tokVar = tokVar->nextArgument();
if (Token::Match(tokVar, pattern1) || Token::Match(tokVar, pattern2)) {
tokVar = tokVar->next();
if (tokVar->str() == "(")
tokVar = tokVar->next();
if (tokVar->varId() > 0) {
const Variable *var = symbolDatabase->getVariableFromVarId(tokVar->varId());
if (var && var->nameToken()->strAt(-1) == "*") {
if (var && var->isPointer()) {
sizeofForStrncmpError(tokVar);
}
}
}
}
}
}
void CheckOther::sizeofForStrncmpError(const Token *tok)
{

View File

@ -4097,6 +4097,12 @@ private:
" return strncmp(buf1, buf1_ex, sizeof(buf1_ex)) == 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:4]: (warning) Passing sizeof(pointer) as the last argument to strncmp.\n", errout.str());
check(
"int fun(const char *buf1) {\n"
" return strncmp(buf1, foo(buf2), sizeof(buf1)) == 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Passing sizeof(pointer) as the last argument to strncmp.\n", errout.str());
}
void check_signOfUnsignedVariable(const char code[], bool inconclusive=false) {