Skip to content

Commit 746beb9

Browse files
committed
Added support for delete and delete[] in invalidDeallocation check (fixes cppcheck-opensource#1773)
1 parent dee5568 commit 746beb9

2 files changed

Lines changed: 28 additions & 9 deletions

File tree

lib/checkautovariables.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,10 @@ void CheckAutoVariables::autoVariables()
147147
errorReturnAddressOfFunctionParameter(tok, tok->strAt(2));
148148
}
149149
// Invalid pointer deallocation
150-
else if (Token::Match(tok, "free ( %var% ) ;") && isAutoVarArray(tok->tokAt(2)->varId())) {
151-
errorInvalidDeallocation(tok);
150+
else if (Token::Match(tok, "free ( %var% ) ;") || Token::Match(tok, "delete [| ]| (| %var% !![")) {
151+
tok = Token::findmatch(tok->next(), "%var%");
152+
if (isAutoVarArray(tok->varId()))
153+
errorInvalidDeallocation(tok);
152154
}
153155
}
154156
}

test/testautovariables.cpp

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -315,13 +315,30 @@ class TestAutoVariables : public TestFixture {
315315
}
316316

317317
void testinvaliddealloc() {
318-
check("int* func1()\n"
319-
"{\n"
320-
"int a;\n"
321-
"char tmp[256];\n"
322-
"free (tmp);\n"
323-
"}\n");
324-
ASSERT_EQUALS(std::string("[test.cpp:5]: (error) Deallocating auto-variable is invalid\n"), errout.str());
318+
check("void func1() {\n"
319+
" char tmp1[256];\n"
320+
" free(tmp1);\n"
321+
" char tmp2[256];\n"
322+
" delete tmp2;\n"
323+
" char tmp3[256];\n"
324+
" delete (tmp3);\n"
325+
" char tmp4[256];\n"
326+
" delete[] (tmp4);\n"
327+
" char tmp5[256];\n"
328+
" delete[] tmp5;\n"
329+
"}");
330+
ASSERT_EQUALS("[test.cpp:3]: (error) Deallocating auto-variable is invalid\n"
331+
"[test.cpp:5]: (error) Deallocating auto-variable is invalid\n"
332+
"[test.cpp:7]: (error) Deallocating auto-variable is invalid\n"
333+
"[test.cpp:9]: (error) Deallocating auto-variable is invalid\n"
334+
"[test.cpp:11]: (error) Deallocating auto-variable is invalid\n", errout.str());
335+
336+
check("void func1() {\n"
337+
" char* tmp1[256];\n"
338+
" init(tmp1);\n"
339+
" delete tmp1[34];\n"
340+
"}");
341+
ASSERT_EQUALS("", errout.str());
325342

326343
check("void f()\n"
327344
"{\n"

0 commit comments

Comments
 (0)