Fixed ticket #338 (Simplify sizeof for pointer arrays) by patch submitted by php-coderrr

http://apps.sourceforge.net/trac/cppcheck/ticket/338
This commit is contained in:
Reijo Tomperi 2009-05-31 22:33:44 +03:00
parent 8822cbb713
commit 2de4c516e9
2 changed files with 48 additions and 5 deletions

View File

@ -1140,6 +1140,8 @@ void Tokenizer::simplifyTokenList()
_typeSize["long"] = sizeof(long);
_typeSize["float"] = sizeof(float);
_typeSize["double"] = sizeof(double);
_typeSize["*"] = sizeof(void *);
for (Token *tok = _tokens; tok; tok = tok->next())
{
if (Token::Match(tok, "class|struct %var%"))
@ -1286,19 +1288,22 @@ void Tokenizer::simplifyTokenList()
// Replace 'sizeof(var)'
for (Token *tok = _tokens; tok; tok = tok->next())
{
// type array [ num ] ;
if (! Token::Match(tok, "%type% %var% [ %num% ] ;"))
if (! Token::Match(tok, "%type% *| %var% [ %num% ] ;"))
continue;
int size = SizeOfType(tok->str().c_str());
const int type_tok = ((tok->next()->str() == "*") ? 1 : 0);
const int varname_tok = type_tok + 1;
const int num_tok = varname_tok + 2;
int size = SizeOfType(tok->tokAt(type_tok)->str().c_str());
if (size <= 0)
continue;
const unsigned int varid = tok->next()->varId();
const unsigned int varid = tok->tokAt(varname_tok)->varId();
if (varid == 0)
continue;
int total_size = size * MathLib::toLongNumber(tok->strAt(3));
int total_size = size * MathLib::toLongNumber(tok->strAt(num_tok));
// Replace 'sizeof(var)' with number
int indentlevel = 0;

View File

@ -79,6 +79,7 @@ private:
TEST_CASE(sizeof5);
TEST_CASE(sizeof6);
TEST_CASE(sizeof7);
TEST_CASE(sizeof8);
TEST_CASE(casting);
TEST_CASE(template1);
@ -542,6 +543,43 @@ private:
ASSERT_EQUALS(" ; INT32 i [ 10 ] ; sizeof ( i [ 0 ] ) ;", sizeof_(code));
}
void sizeof8()
{
{
const char code[] = "void f()\n"
"{\n"
" char* ptrs[2];\n"
" int a = sizeof( ptrs );\n"
"}\n";
std::ostringstream oss;
oss << (sizeof(void *) * 2);
ASSERT_EQUALS(" void f ( ) { char * ptrs [ 2 ] ; int a ; a = " + oss.str() + " ; }", sizeof_(code));
}
{
const char code[] = "void f()\n"
"{\n"
" char* ptrs[55];\n"
" int a = sizeof( ptrs );\n"
"}\n";
std::ostringstream oss;
oss << (sizeof(void *) * 55);
ASSERT_EQUALS(" void f ( ) { char * ptrs [ 55 ] ; int a ; a = " + oss.str() + " ; }", sizeof_(code));
}
{
const char code[] = "void f()\n"
"{\n"
" char* ptrs;\n"
" int a = sizeof( ptrs );\n"
"}\n";
std::ostringstream oss;
oss << sizeof(void *);
TODO_ASSERT_EQUALS(" void f ( ) { char * ptrs ; int a ; a = " + oss.str() + " ; }", sizeof_(code));
}
}
void casting()
{
const char code[] = "void f()\n"