Skip to content

Commit

Permalink
Fix FP memleak with outparam allocation (f'up to #12186) (danmar#5677)
Browse files Browse the repository at this point in the history
I wonder if it is worth trying to get this right. We also have FPs when
the return value is assigned to a variable, and that seems much harder
to fix.
  • Loading branch information
chrchr-github committed Nov 19, 2023
1 parent 4addad1 commit cd21918
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/checkleakautovar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,23 @@ void CheckLeakAutoVar::ret(const Token *tok, VarInfo &varInfo, const bool isEndO
}
}

// don't warn when returning after checking return value of outparam allocation
const Scope* scope = tok->scope();
if (scope->type == Scope::ScopeType::eIf || scope->type== Scope::ScopeType::eElse) {
if (scope->type == Scope::ScopeType::eElse) {
scope = scope->bodyStart->tokAt(-2)->scope();
}
const Token* const ifEnd = scope->bodyStart->previous();
const Token* const ifStart = ifEnd->link();
const Token* const alloc = it->second.allocTok;
if (precedes(ifStart, alloc) && succeeds(ifEnd, alloc)) {
int argn{};
if (const Token* ftok = getTokenArgumentFunction(alloc, argn))
if (Token::Match(ftok->next()->astParent(), "%comp%"))
continue;
}
}

// return deallocated pointer
if (used != PtrUsage::NONE && it->second.status == VarInfo::DEALLOC)
deallocReturnError(tok, it->second.allocTok, var->name());
Expand Down
18 changes: 18 additions & 0 deletions test/cfg/gnu.c
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,24 @@ void memleak_asprintf5(char* p) {
// cppcheck-suppress memleak
}

void memleak_asprintf6(const char* fmt, const int arg) {
char* ptr;
if (-1 == asprintf(&ptr, fmt, arg))
return;
printf("%s", ptr);
free(ptr);
}

void memleak_asprintf7(const char* fmt, const int arg) {
char* ptr;
if (asprintf(&ptr, fmt, arg) != -1) {
printf("%s", ptr);
free(ptr);
}
else
return;
}

void memleak_xmalloc()
{
char *p = (char*)xmalloc(10);
Expand Down

0 comments on commit cd21918

Please sign in to comment.