From a69a5705056e1c5535ebabdf6c5aa4c5cac81844 Mon Sep 17 00:00:00 2001 From: Rikard Falkeborn Date: Thu, 25 Jul 2019 21:09:23 +0200 Subject: [PATCH] Fix FP leakVarNotUsed with freopen() and stdin (#2034) One usecase for freopen() is to redirect input and output streams to files. For that, the return value is not needed. --- lib/checkmemoryleak.cpp | 9 +++++++++ test/testmemleak.cpp | 5 +++++ 2 files changed, 14 insertions(+) diff --git a/lib/checkmemoryleak.cpp b/lib/checkmemoryleak.cpp index 702ef52ad..736f735a2 100644 --- a/lib/checkmemoryleak.cpp +++ b/lib/checkmemoryleak.cpp @@ -1006,6 +1006,15 @@ void CheckMemoryLeakNoVar::checkForUnusedReturnValue(const Scope *scope) if (tok != tok->next()->astOperand1()) continue; + if (getReallocationType(tok, 0) == File) { + const Library::AllocFunc *f = mSettings->library.getReallocFuncInfo(tok); + if (f && f->reallocArg > 0 && f->reallocArg <= numberOfArguments(tok)) { + const Token* arg = getArguments(tok).at(f->reallocArg - 1); + if (Token::Match(arg, "stdin|stdout|stderr")) + continue; + } + } + // get ast parent, skip casts const Token *parent = tok->next()->astParent(); while (parent && parent->str() == "(" && !parent->astOperand2()) diff --git a/test/testmemleak.cpp b/test/testmemleak.cpp index 868ba7180..9e902ae6c 100644 --- a/test/testmemleak.cpp +++ b/test/testmemleak.cpp @@ -2329,6 +2329,11 @@ private: "}\n"); ASSERT_EQUALS("[test.cpp:3]: (error) Return value of allocation function 'freopen' is not stored.\n", errout.str()); + check("void foo() {\n" + " freopen(\"file.txt\", \"r\", stdin);\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + check("struct Holder {\n" " Holder(FILE* f) : file(f) {}\n" " ~Holder() { fclose(file); }\n"