[clang] [analyzer] Implemented the DanglingPtrDeref checker to detect use-after-scope lifetime errors (PR #209278)

DonĂ¡t Nagy via cfe-commits cfe-commits at lists.llvm.org
Tue Jul 14 05:07:25 PDT 2026


================
@@ -0,0 +1,86 @@
+// RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.cplusplus.ReportDanglingPtrDeref \
+// RUN:   -analyzer-config cfg-lifetime=true -analyzer-output=text -verify %s
+
+void test_case_one() {
+  int *ptr = nullptr;
+  {
+    int num = 5;
+    ptr = #
+  }
+  // expected-note at -1 {{'num' is destroyed here}}
+  *ptr = 6;
+  // expected-warning at -1 {{Use of 'num' after its lifetime ended}}
+  // expected-note at -2    {{Use of 'num' after its lifetime ended}}
+}
+
+void test_case_two() {
+  int *ptr_one = nullptr;
+  int *ptr_two = nullptr;
+  {
+    int n = 1;
+    int m = 2;
+    ptr_one = &n;
+    ptr_two = &m;
+  }
+  // expected-note at -1 {{'n' is destroyed here}}
+  // expected-note at -2 {{'m' is destroyed here}}
+  *ptr_one = 6;
+  *ptr_two = 7; 
+  // expected-warning at -2 {{Use of 'n' after its lifetime ended}}
+  // expected-note at -3    {{Use of 'n' after its lifetime ended}}
----------------
NagyDonat wrote:

This is the default behavior, which can be observed on almost all checkers (AFAIK the only exceptions are `security.ArrayBound` and `core.BitwiseShift` where I implemented distinct short and full descriptions).

Conceptually, the warning diagnostic (short description of the `BugReport`) is a single-line summary of the whole bug; while the note diagnostic that appears on the same line (the non-short description) is the last one among the collection of "note" diagnostics that describe the bug together.

In our tests the identical warning and node appears to be very redundant (and I was also very confused when I first noticed this), but in actual UIs they appear in a reasonable way:
- usually the warning message is displayed first as a title/summary of the bug report (and e.g. in CodeChecker AFAIK this is not displayed inline);
- then the various note diagnostics are listed to explain the execution path;
- finally, the last note tag (which is identical to the warning message) shows that at the end of the execution path we reached the problematic situation.

In the above-mentioned two checkers I implemented logic where there is a difference between the warning (which is terse) and the final note (which contains more details), but this is not necessary for all checkers.

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


More information about the cfe-commits mailing list