From e33985dbf0e45b52f772e463d88544f129d76637 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sat, 22 Nov 2008 11:30:50 +0000 Subject: [PATCH] Memory leak: Handle conditions that are always true / false --- CheckMemoryLeak.cpp | 14 ++++++++++++-- testmemleak.cpp | 24 +++++++++++++++++++++++- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/CheckMemoryLeak.cpp b/CheckMemoryLeak.cpp index 6e17cacf5..b6997c392 100644 --- a/CheckMemoryLeak.cpp +++ b/CheckMemoryLeak.cpp @@ -370,7 +370,7 @@ TOKEN *CheckMemoryLeakClass::getcode(const TOKEN *tok, std::list dealloctype = dealloc; } - // if else switch + // if else switch if ( Tokenizer::Match(tok, "if ( %var1% )", varnames) || Tokenizer::Match(tok, "if ( %var1% != 0 )", varnames) || Tokenizer::Match(tok, "if ( 0 != %var1% )", varnames) ) @@ -381,7 +381,15 @@ TOKEN *CheckMemoryLeakClass::getcode(const TOKEN *tok, std::list else if ( Tokenizer::Match(tok, "if (") && notvar(Tokenizer::gettok(tok,2), varnames) ) { addtoken("if(!var)"); - } + } + else if ( Tokenizer::Match(tok, "if (") && _tokenizer->alwaysTrue(tok->next) ) + { + addtoken("if(true)"); + } + else if ( Tokenizer::Match(tok, "if (") && _tokenizer->alwaysTrue(tok->next) ) + { + addtoken("if(false)"); + } else if ( Tokenizer::Match(tok, "if") ) { // Check if the condition depends on var somehow.. @@ -599,6 +607,8 @@ void CheckMemoryLeakClass::simplifycode(TOKEN *tok) if ( Tokenizer::Match(tok2,"[;{}] if ;") || Tokenizer::Match(tok2,"[;{}] if(var) ;") || Tokenizer::Match(tok2,"[;{}] if(!var) ;") || + Tokenizer::Match(tok2,"[;{}] if(true) ;") || + Tokenizer::Match(tok2,"[;{}] if(false) ;") || Tokenizer::Match(tok2,"[;{}] ifv ;") ) { if ( ! Tokenizer::Match(Tokenizer::gettok(tok2,3), "else") ) diff --git a/testmemleak.cpp b/testmemleak.cpp index 960f37669..ca247ec70 100644 --- a/testmemleak.cpp +++ b/testmemleak.cpp @@ -84,7 +84,9 @@ private: TEST_CASE( if2 ); TEST_CASE( if3 ); TEST_CASE( if4 ); - TEST_CASE( if5 ); + TEST_CASE( if5 ); + + TEST_CASE( alwaysTrue ); TEST_CASE( forwhile1 ); TEST_CASE( forwhile2 ); @@ -453,6 +455,26 @@ private: ASSERT_EQUALS( std::string(""), err ); } + + + + + void alwaysTrue() + { + check( "void f()\n" + "{\n" + " char *p = 0;\n" + " for (;;)\n" + " {\n" + " p = malloc(256);\n" + " if (1)\n" + " break;\n" + " }\n" + " free(p);\n" + "}\n" ); + std::string err( errout.str() ); + ASSERT_EQUALS( std::string(""), err ); + }