Fixed #2115 (new check: endless loop (unsigned comparison that is always true))

This commit is contained in:
PKEuS 2011-10-09 20:35:46 +02:00 committed by Daniel Marjamäki
parent 1c9ae6937c
commit 5f9b916dcc
2 changed files with 18 additions and 4 deletions

View File

@ -2594,25 +2594,25 @@ void CheckOther::checkSignOfUnsignedVariable()
// check all the code in the function
for (const Token *tok = scope->classStart; tok && tok != scope->classStart->link(); tok = tok->next())
{
if (Token::Match(tok, "(|&&|%oror% %var% <|<= 0 )|&&|%oror%") && tok->next()->varId())
if (Token::Match(tok, ";|(|&&|%oror% %var% <|<= 0 ;|)|&&|%oror%") && tok->next()->varId())
{
const Variable * var = symbolDatabase->getVariableFromVarId(tok->next()->varId());
if (var && var->typeEndToken()->isUnsigned())
unsignedLessThanZeroError(tok->next(), tok->next()->str());
}
else if (Token::Match(tok, "(|&&|%oror% 0 > %var% )|&&|%oror%") && tok->tokAt(3)->varId())
else if (Token::Match(tok, ";|(|&&|%oror% 0 > %var% ;|)|&&|%oror%") && tok->tokAt(3)->varId())
{
const Variable * var = symbolDatabase->getVariableFromVarId(tok->tokAt(3)->varId());
if (var && var->typeEndToken()->isUnsigned())
unsignedLessThanZeroError(tok->tokAt(3), tok->strAt(3));
}
else if (Token::Match(tok, "(|&&|%oror% 0 <= %var% )|&&|%oror%") && tok->tokAt(3)->varId())
else if (Token::Match(tok, ";|(|&&|%oror% 0 <= %var% ;|)|&&|%oror%") && tok->tokAt(3)->varId())
{
const Variable * var = symbolDatabase->getVariableFromVarId(tok->tokAt(3)->varId());
if (var && var->typeEndToken()->isUnsigned())
unsignedPositiveError(tok->tokAt(3), tok->strAt(3));
}
else if (Token::Match(tok, "(|&&|%oror% %var% >= 0 )|&&|%oror%") && tok->next()->varId())
else if (Token::Match(tok, ";|(|&&|%oror% %var% >= 0 ;|)|&&|%oror%") && tok->next()->varId())
{
const Variable * var = symbolDatabase->getVariableFromVarId(tok->next()->varId());
if (var && var->typeEndToken()->isUnsigned())

View File

@ -3297,6 +3297,20 @@ private:
void checkSignOfUnsignedVariable()
{
check_signOfUnsignedVariable(
"void foo() {\n"
" for(unsigned char i = 10; i >= 0; i--)"
" printf(\"%u\", i);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned variable 'i' is positive is always true.\n", errout.str());
check_signOfUnsignedVariable(
"void foo(bool b) {\n"
" for(unsigned int i = 10; b || i >= 0; i--)"
" printf(\"%u\", i);\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (style) Checking if unsigned variable 'i' is positive is always true.\n", errout.str());
check_signOfUnsignedVariable(
"bool foo(unsigned int x) {\n"
" if (x < 0)"