Skip to content

Commit a80101f

Browse files
committed
CheckMemoryLeak: Fix FP for allocation functions that register memory before returning it
1 parent fb685f0 commit a80101f

3 files changed

Lines changed: 20 additions & 3 deletions

File tree

‎lib/checkmemoryleak.cpp‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -449,8 +449,11 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::functionReturnType(const Function* f
449449
if (Token::Match(tok, "[(,] %varid% [,)]", varid)) {
450450
return No;
451451
}
452-
if (tok->str() == "return")
453-
return allocType;
452+
if (Token::Match(tok, "[(,] & %varid% [.,)]", varid)) {
453+
return No;
454+
}
455+
if (allocType == No && tok->str() == "return")
456+
return No;
454457
}
455458

456459
return allocType;

‎test/testmemleak.cpp‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ class TestMemleakInFunction : public TestFixture {
253253
TEST_CASE(allocfunc11);
254254
TEST_CASE(allocfunc12); // #3660: allocating and returning non-local pointer => not allocfunc
255255
TEST_CASE(allocfunc13); // Ticket #4494 and #4540 - class function
256+
TEST_CASE(allocfunc14); // Use pointer before returning it
256257

257258
TEST_CASE(throw1);
258259
TEST_CASE(throw2);
@@ -2827,6 +2828,19 @@ class TestMemleakInFunction : public TestFixture {
28272828
ASSERT_EQUALS("[test.cpp:11]: (error) Memory leak: a\n", errout.str());
28282829
}
28292830

2831+
void allocfunc14() { // use pointer before returning it
2832+
check("static struct ABC * newabc() {\n"
2833+
" struct ABC *abc = malloc(sizeof(struct ABC));\n"
2834+
" init_abc(&abc->a);\n" // <- might take address
2835+
" return abc;\n"
2836+
"}\n"
2837+
"\n"
2838+
"static void f() {\n"
2839+
" struct ABC *abc = newabc();\n"
2840+
"}");
2841+
ASSERT_EQUALS("", errout.str());
2842+
}
2843+
28302844
void throw1() {
28312845
check("void foo()\n"
28322846
"{\n"

‎test/testother.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5490,7 +5490,7 @@ class TestOther : public TestFixture {
54905490
" std::cout << 3 << -1 ;\n"
54915491
"}");
54925492
ASSERT_EQUALS("", errout.str());
5493-
5493+
54945494
check("x = y ? z << $-1 : 0;\n");
54955495
ASSERT_EQUALS("", errout.str());
54965496
}

0 commit comments

Comments
 (0)