Fixed #425 (False positive: usage of char variable.. c = c & 0x03)

Using char variables in bit operations are ok if:
 * the result is stored in a char
 * the variable is and'ed with a number that is less than 0x100
This commit is contained in:
Daniel Marjamäki 2009-06-20 19:24:58 +02:00
parent d1d9c9a9c9
commit 8a3ec4549b
2 changed files with 44 additions and 3 deletions

View File

@ -752,10 +752,26 @@ void CheckOther::CheckCharVariable()
break;
}
std::string tempFirst = "%var% [&|] " + tok->str();
std::string tempSecond = tok->str() + " [&|]";
if (Token::Match(tok2, tempFirst.c_str()) || Token::Match(tok2, tempSecond.c_str()))
if (Token::Match(tok2, "[;{}] %var% = %any% [&|] %any% ;"))
{
// is the char variable used in the calculation?
if (tok2->tokAt(3)->varId() != tok->varId() && tok2->tokAt(5)->varId() != tok->varId())
continue;
// it's ok with a bitwise and where the other operand is 0xff or less..
if (std::string(tok2->strAt(4)) == "&")
{
if (tok2->tokAt(3)->isNumber() && MathLib::isGreater("0x100", tok2->strAt(3)))
continue;
if (tok2->tokAt(5)->isNumber() && MathLib::isGreater("0x100", tok2->strAt(5)))
continue;
}
// is the result stored in a short|int|long?
if (!Token::findmatch(_tokenizer->tokens(), "short|int|long %varid%", tok2->next()->varId()))
continue;
// This is an error..
charBitOpError(tok2);
break;
}

View File

@ -39,6 +39,8 @@ private:
TEST_CASE(bitop1);
TEST_CASE(bitop2);
TEST_CASE(return1);
TEST_CASE(assignChar);
TEST_CASE(and03);
}
void check(const char code[])
@ -93,6 +95,7 @@ private:
{
check("void foo()\n"
"{\n"
" int result = 0;\n"
" char ch;\n"
" result = a | ch;\n"
"}\n");
@ -118,6 +121,28 @@ private:
"}\n");
ASSERT_EQUALS("", errout.str());
}
void assignChar()
{
check("void foo()\n"
"{\n"
" char c;\n"
" c = c & 0x123;\n"
"}\n");
ASSERT_EQUALS("", errout.str());
}
void and03()
{
check("void foo()\n"
"{\n"
" char c;\n"
" int i = c & 0x03;\n"
"}\n");
ASSERT_EQUALS("", errout.str());
}
};
REGISTER_TEST(TestCharVar)