diff --git a/CheckOther.cpp b/CheckOther.cpp index f65e3b620..19b2cfd58 100644 --- a/CheckOther.cpp +++ b/CheckOther.cpp @@ -550,13 +550,20 @@ void CheckVariableScope() } if ( indentlevel > 0 && func && strchr("{};", tok->str[0]) ) { - // Variable declaration? - if (match(tok->next, "var var ;")) - CheckVariableScope_LookupVar( tok->next, getstr(tok, 2) ); + // First token of statement.. + TOKEN *tok1 = tok->next; + + if (strcmp(tok1->str,"return")==0 || + strcmp(tok1->str,"delete")==0 || + strcmp(tok1->str,"else")==0) + continue; // Variable declaration? - else if (match(tok->next, "var var =")) - CheckVariableScope_LookupVar( tok->next, getstr(tok, 2) ); + if (match(tok1, "var var ;") || + match(tok1, "var var =") ) + { + CheckVariableScope_LookupVar( tok1, getstr(tok1, 1) ); + } } } @@ -568,7 +575,6 @@ static void CheckVariableScope_LookupVar( const TOKEN *tok1, const char varname[ const TOKEN *tok = tok1; // Skip the variable declaration.. - tok = tok->next; while ( tok->str[0] != ';' ) tok = tok->next; diff --git a/main.cpp b/main.cpp index ae98aae6f..0c8fe3c0e 100644 --- a/main.cpp +++ b/main.cpp @@ -219,6 +219,9 @@ static void CppCheck(const char FileName[]) // Dangerous usage of strtok // Disabled because it generates false positives //WarningStrTok(); + + // Variable scope + CheckVariableScope(); } diff --git a/tests.cpp b/tests.cpp index ce88c0e86..f30a825fe 100644 --- a/tests.cpp +++ b/tests.cpp @@ -724,16 +724,33 @@ static void unused_variable() " }\n" "}\n"; check( CheckVariableScope, __LINE__, test2, "[test.cpp:3] The scope of the variable 'i' can be limited\n" ); -/* - const char test3[] = "void f()\n" + + + const char test3[] = "static void DeleteNextToken(TOKEN *tok)\n" "{\n" - " int i = 0;\n" - " while (abc)\n" - " {\n" - " i = i + 1;\n" - " }\n" + " TOKEN *next = tok->next;\n" + " tok->next = next->next;\n" + " free(next->str);\n" + " delete next;\n" "}\n"; check( CheckVariableScope, __LINE__, test3, "" ); -*/ + + + + const char test4[] = "static void f()\n" + "{\n" + " bool special = false;\n" + " do\n" + " {\n" + " // Special sequence\n" + " if (special)\n" + " special = false;\n" + " else\n" + " special = (c == \'\\\');\n" + " }\n" + " while (special || c != \'\"\');\n" + "}\n"; + check( CheckVariableScope, __LINE__, test4, "" ); + }