Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions lib/checkmemoryleak.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -744,8 +744,15 @@ bool CheckMemoryLeakStructMember::isMalloc(const Variable *variable) const
for (const Token *tok2 = variable->nameToken(); tok2 && tok2 != variable->scope()->bodyEnd; tok2 = tok2->next()) {
if (Token::Match(tok2, "= %varid% [;=]", declarationId))
return false;
if (Token::Match(tok2, "%varid% = %name% (", declarationId) && mSettings->library.getAllocFuncInfo(tok2->tokAt(2)))
alloc = true;
if (Token::Match(tok2, "%varid% =", declarationId)) {
const Token* tok3 = tok2->tokAt(1)->astOperand2();
while (tok3 && tok3->isCast())
tok3 = tok3->astOperand2() ? tok3->astOperand2() : tok3->astOperand1();
if ((tok3 && Token::Match(tok3->tokAt(-1), "%name% (") && mSettings->library.getAllocFuncInfo(tok3->tokAt(-1))) ||
(Token::simpleMatch(tok3, "new") && tok3->isCpp())) {
alloc = true;
}
}
}
return alloc;
}
Expand Down
24 changes: 24 additions & 0 deletions test/testmemleak.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1673,6 +1673,7 @@ class TestMemleakStructMember : public TestFixture {
TEST_CASE(assign2);
TEST_CASE(assign3);
TEST_CASE(assign4); // #11019
TEST_CASE(assign5);

// Failed allocation
TEST_CASE(failedAllocation);
Expand Down Expand Up @@ -1919,6 +1920,29 @@ class TestMemleakStructMember : public TestFixture {
ASSERT_EQUALS("", errout_str());
}

void assign5() {
check("struct S { int fd; };\n"
"void f() {\n"
" struct S* s = (struct S*)malloc(sizeof(struct S));\n"
" s->fd = open(\"abc\", O_RDWR | O_NOCTTY);\n"
" free(s);\n"
"}\n"
"void g() {\n"
" struct S* s = static_cast<struct S*>(malloc(sizeof(struct S)));\n"
" s->fd = open(\"abc\", O_RDWR | O_NOCTTY);\n"
" free(s);\n"
"}\n"
"void h() {\n"
" S* s = new S;\n"
" s->fd = open(\"abc\", O_RDWR | O_NOCTTY);\n"
" delete s;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5:5]: (error) Resource leak: s.fd [resourceLeak]\n"
"[test.cpp:10:5]: (error) Resource leak: s.fd [resourceLeak]\n"
"[test.cpp:16:1]: (error) Resource leak: s.fd [resourceLeak]\n",
errout_str());
}

void failedAllocation() {
check("static struct ABC * foo()\n"
"{\n"
Expand Down
Loading