[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
Tue Aug 26 08:10:07 PDT 2025


================
@@ -3068,12 +3124,242 @@ void MallocChecker::checkDeadSymbols(SymbolReaper &SymReaper,
   C.addTransition(state->set<RegionState>(RS), N);
 }
 
+// Helper function to check if a name is a recognized smart pointer name
+static bool isSmartPtrName(StringRef Name) {
+  return Name == "unique_ptr" || Name == "shared_ptr";
+}
+
+// Allowlist of owning smart pointers we want to recognize.
+// Start with unique_ptr and shared_ptr. (intentionally exclude weak_ptr)
+static bool isSmartOwningPtrType(QualType QT) {
+  QT = QT->getCanonicalTypeUnqualified();
+
+  // First try TemplateSpecializationType (for std smart pointers)
+  if (const auto *TST = QT->getAs<TemplateSpecializationType>()) {
+    const TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
+    if (!TD)
+      return false;
+
+    const auto *ND = dyn_cast_or_null<NamedDecl>(TD->getTemplatedDecl());
+    if (!ND)
+      return false;
+
+    // Check if it's in std namespace
+    if (!isWithinStdNamespace(ND))
+      return false;
+
+    return isSmartPtrName(ND->getName());
+  }
+
+  // Also try RecordType (for custom smart pointer implementations)
+  if (const auto *RD = QT->getAsCXXRecordDecl()) {
+    // Accept any custom unique_ptr or shared_ptr implementation
+    return isSmartPtrName(RD->getName());
+  }
----------------
NagyDonat wrote:

What is the practical purpose of this block?

As far as I see this block returns `true` when it encounters non-template classes named `unique_ptr` or `shared_ptr`, and I don't think that this is an established coding pattern which deserves a separate branch. Is this a block that will never be entered during real-world use of the analyzer or do I misunderstand something here?

(If I understand correctly your tests rely on this branch, but I think it's inelegant to tweak the behavior of the actual software in order to slightly simplify the test code. I would prefer using [or writing] a suitable system header simulator.)

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


More information about the cfe-commits mailing list