Fixed #5771 (false positive: (warning) When using 'char' variables in bit operations, sign extension can generate unexpected results.)

This commit is contained in:
Daniel Marjamäki 2014-05-13 15:53:31 +02:00
parent 146bf11aa7
commit 7ecdb30308
2 changed files with 29 additions and 0 deletions

View File

@ -168,6 +168,21 @@ static bool isOppositeCond(const Token * const cond1, const Token * const cond2,
(comp1 == ">=" && comp2 == "<"));
}
static bool isPossibleCast(const Token * const startPar)
{
if (!Token::Match(startPar, "( %type%"))
return false;
const Token *tok;
for (tok = startPar->tokAt(2); tok; tok = tok->next()) {
if (tok->str() == ")")
return true;
if (tok->varId()>0)
return false;
if (!Token::Match(tok,"%type%|*|&"))
return false;
}
return tok != nullptr;
}
//----------------------------------------------------------------------------------
// The return value of fgetc(), getc(), ungetc(), getchar() etc. is an integer value.
@ -2104,6 +2119,10 @@ void CheckOther::checkCharVariable()
else
continue;
// (x) & y => if x is a possible type then assume & is a address-of operator
if (Token::simpleMatch(tok->previous(), ") &") && isPossibleCast(tok->linkAt(-1)))
continue;
// it's ok with a bitwise and where the other operand is 0xff or less..
if (tok->str() == "&" && tok2 && tok2->isNumber() && MathLib::isGreater("0x100", tok2->str()))
continue;

View File

@ -39,6 +39,7 @@ private:
TEST_CASE(bitop1);
TEST_CASE(bitop2);
TEST_CASE(bitop3);
TEST_CASE(bitop4); // (long)&c
TEST_CASE(return1);
TEST_CASE(assignChar);
TEST_CASE(and03);
@ -160,6 +161,15 @@ private:
ASSERT_EQUALS("[test.cpp:2]: (warning) When using 'char' variables in bit operations, sign extension can generate unexpected results.\n", errout.str());
}
void bitop4() {
check("long f(char c) {\n"
" long a;\n"
" a = (long)&c;\n"
" return a;\n"
"}");
ASSERT_EQUALS("", errout.str());
}
void return1() {
check("void foo()\n"
"{\n"