Fix FP memleak with outparam allocation (f'up to #12186) (#5677)

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.
This commit is contained in:
chrchr-github 2023-11-19 19:51:32 +01:00 committed by GitHub
parent 4addad1643
commit cd21918520
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 0 deletions

View File

@ -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());

View File

@ -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);