使用Fortify静态代码分析器检测C++11 std::unique_ptr时出现内存泄漏告警
Let's start with why this false positive is popping up: Fortify SCA 19.2.0 is a fairly old version, and its support for C++11 smart pointers isn't fully polished—it fails to recognize that std::unique_ptr automatically cleans up its managed memory when it goes out of scope (right at the end of your httpServerThread function, in this case).
Here are practical, actionable solutions you can use:
Suppress the false positive with Fortify inline comments
If you can't upgrade your Fortify version right now, this is the fastest fix. Fortify supports special inline comments to tell the analyzer to ignore specific false alerts. Add a comment next to yourunique_ptrdeclaration to suppress the "LEAKED_RESOURCE" warning:void *httpServerThread(void *arg) { std::unique_ptr<int> i(new int(1)); //-V LEAKED_RESOURCE:1 return NULL; }The
-Vflag tells Fortify to skip checking for the specified issue code at that line.Upgrade your Fortify SCA version
This is the most long-term solution. Newer Fortify releases (20.x and later) have much better support for C++11/14/17 features, including proper recognition ofstd::unique_ptr's RAII behavior. Upgrading will eliminate this false positive entirely without needing any workarounds.Implement a custom
make_uniquefor C++11
Even thoughstd::make_uniquewas added in C14, you can roll your own simple version for C11. Some static analyzers handle this wrapper better than directnewinsideunique_ptrconstruction:template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } // Use it in your thread function like this: void *httpServerThread(void *arg) { auto i = make_unique<int>(1); return NULL; }This doesn't change the underlying memory management, but it might help Fortify recognize the pointer is being managed by a smart pointer.
内容的提问来源于stack exchange,提问作者Albin Paul

