[clang] [analyzer] MallocChecker – Fix false positive leak for smart pointers in temporary objects (PR #152751)

Donát Nagy via cfe-commits cfe-commits at lists.llvm.org
Fri Aug 29 05:40:27 PDT 2025


================
@@ -0,0 +1,232 @@
+// RUN: %clang_analyze_cc1 -verify -analyzer-output=text %s \
+// RUN:   -analyzer-checker=core \
+// RUN:   -analyzer-checker=cplusplus \
+// RUN:   -analyzer-checker=unix \
+// RUN:   -analyzer-checker=unix.Malloc
+
+#include "Inputs/system-header-simulator-for-malloc.h"
+
+//===----------------------------------------------------------------------===//
+// unique_ptr test cases 
+//===----------------------------------------------------------------------===//
+namespace unique_ptr_tests {
+
+// Custom unique_ptr implementation for testing
+template <typename T>
+struct unique_ptr {
+  T* ptr;
+  unique_ptr(T* p) : ptr(p) {}
+  ~unique_ptr() { delete ptr; }
----------------
NagyDonat wrote:

Although the `delete ptr` in this destructor accurately reflects the behavior of `unique_ptr`, it is unfortunately a serious confounder for testing the heuristic that is added by your commit.

Your new logic tries to eliminate false positives in situations where an object is owned by a smart pointer, but the analyzer reports a resource leak because it either fails to execute the smart pointer destructor or doesn't understand the body of the destructor (which is more likely with `shared_ptr`, where the analyzer typically can't follow the reference counting). With this nice destructor the results of the tests are inconclusive: even if the new heuristic fails, the testcases may still succeed if the analyzer executes and understands this destructor.

For this reason I would suggest using an intentionally broken destructor in this mock class:
```suggestion
  ~unique_ptr() {
    // This destructor intentionally doesn't delete 'ptr' to validate that the
    // heuristic trusts that smart pointers (based on their class name) will
    // release the pointee even if it doesn't understand their destructor.
  }
```

Note that this also applies to the mocked `shared_ptr` that appears later.

https://github.com/llvm/llvm-project/pull/152751


More information about the cfe-commits mailing list