diff --git a/CheckMemoryLeak.cpp b/CheckMemoryLeak.cpp index 0b1fca452..eb7946f5d 100644 --- a/CheckMemoryLeak.cpp +++ b/CheckMemoryLeak.cpp @@ -249,6 +249,7 @@ static TOKEN *getcode(const TOKEN *tok, const char varname[]) Match(tok, "if ( %var1% != NULL )", varnames) ) { addtoken("if(var)"); + tok = gettok(tok, 3); // Make sure the "use" will not be added } else if ( Match(tok, "if ( ! %var1% )", varnames) || Match(tok, "if ( unlikely ( ! %var1% ) )", varnames) || @@ -518,7 +519,12 @@ static void CheckMemoryLeak_CheckScope( const TOKEN *Tok1, const char varname[] } - if ( findmatch(tok, "alloc ; if continue ;") ) + if ( findmatch(tok, "loop alloc ;") ) + { + MemoryLeak(findmatch(tok, "loop alloc ;"), varname); + } + + else if ( findmatch(tok, "alloc ; if continue ;") ) { MemoryLeak(gettok(findmatch(tok, "alloc ; if continue ;"), 3), varname); } diff --git a/testmemleak.cpp b/testmemleak.cpp index 92eb8763e..0ce861814 100644 --- a/testmemleak.cpp +++ b/testmemleak.cpp @@ -46,7 +46,8 @@ public: TEST_CASE( forwhile1 ); TEST_CASE( forwhile2 ); - + TEST_CASE( forwhile3 ); + TEST_CASE( forwhile4 ); TEST_CASE( switch1 ); TEST_CASE( switch2 ); @@ -298,8 +299,36 @@ public: } + void forwhile3() + { + check( "void f()\n" + "{\n" + " char *str = 0;\n" + " for (int i = 0; i < 10; i++)\n" + " {\n" + " str = strdup(\"hello\");\n" + " }\n" + " free(str);\n" + "}\n" ); + ASSERT_EQUALS( std::string("[test.cpp:4]: Memory leak: str\n"), errout.str() ); + } + void forwhile4() + { + check( "void f()\n" + "{\n" + " char *str = 0;\n" + " for (int i = 0; i < 10; i++)\n" + " {\n" + " str = strdup(\"hello\");\n" + " if (str) { }\n" + " }\n" + " free(str);\n" + "}\n" ); + ASSERT_EQUALS( std::string("[test.cpp:4]: Memory leak: str\n"), errout.str() ); + } +