Skip to content

Commit 791051c

Browse files
Fix #9228 (FN common realloc mistake with assignment of NULL)
Do not match for assignments with NULL.
1 parent da8ad9c commit 791051c

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

lib/checkmemoryleak.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -547,7 +547,7 @@ void CheckMemoryLeakInFunction::checkReallocUsage()
547547

548548
// Check that another copy of the pointer wasn't saved earlier in the function
549549
if (Token::findmatch(scope->bodyStart, "%name% = %varid% ;", tok, tok->varId()) ||
550-
Token::findmatch(scope->bodyStart, "[{};] %varid% = *| %name% .| %name%| [;=]", tok, tok->varId()))
550+
Token::findmatch(scope->bodyStart, "[{};] %varid% = *| %var% .| %var%| [;=]", tok, tok->varId()))
551551
continue;
552552

553553
// Check if the argument is known to be null, which means it is not a memory leak

test/testmemleak.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,7 @@ class TestMemleakInFunction : public TestFixture {
169169
TEST_CASE(realloc21);
170170
TEST_CASE(realloc22);
171171
TEST_CASE(realloc23);
172+
TEST_CASE(realloc24); // #9228
172173
TEST_CASE(reallocarray1);
173174
}
174175

@@ -410,6 +411,35 @@ class TestMemleakInFunction : public TestFixture {
410411
ASSERT_EQUALS("", errout.str());
411412
}
412413

414+
void realloc24() { // #9228
415+
check("void f() {\n"
416+
"void *a = NULL;\n"
417+
"a = realloc(a, 20);\n"
418+
"}");
419+
ASSERT_EQUALS("", errout.str());
420+
421+
check("void f() {\n"
422+
"void *a = NULL;\n"
423+
"a = malloc(10);\n"
424+
"a = realloc(a, 20);\n"
425+
"}");
426+
ASSERT_EQUALS("[test.cpp:4]: (error) Common realloc mistake: \'a\' nulled but not freed upon failure\n", errout.str());
427+
428+
check("void f() {\n"
429+
"void *a = std::nullptr;\n"
430+
"a = malloc(10);\n"
431+
"a = realloc(a, 20);\n"
432+
"}");
433+
ASSERT_EQUALS("[test.cpp:4]: (error) Common realloc mistake: \'a\' nulled but not freed upon failure\n", errout.str());
434+
435+
check("void f(char *b) {\n"
436+
"void *a = NULL;\n"
437+
"a = b;\n"
438+
"a = realloc(a, 20);\n"
439+
"}");
440+
ASSERT_EQUALS("", errout.str());
441+
}
442+
413443
void reallocarray1() {
414444
check("void foo()\n"
415445
"{\n"

0 commit comments

Comments
 (0)