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

Benedek Kaibas via cfe-commits cfe-commits at lists.llvm.org
Tue Jul 14 05:51:50 PDT 2026


================
@@ -97,10 +113,37 @@ void LifetimeModeling::checkPostCall(const CallEvent &Call,
   C.addTransition(State);
 }
 
+void LifetimeModeling::checkLifetimeEnd(const VarDecl *VD,
+                                        CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  if (!VD)
+    return;
+
+  SVal SourceVal = State->getLValue(VD, C.getStackFrame());
+  if (const MemRegion *SourceValRegion = SourceVal.getAsRegion()) {
+    State = State->add<DeallocatedSourceSet>(SourceValRegion);
+    C.addTransition(State);
+  }
+}
+
+void LifetimeModeling::checkPreStmt(const DeclStmt *DS,
+                                    CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  for (const auto *I : DS->decls()) {
+    if (const VarDecl *VD = dyn_cast<VarDecl>(I)) {
----------------
benedekaibas wrote:

> Note that there are 3 different cases of structured binding (array, struct, tuple-like type).
> 
> When you bind to tuple-like types, the returned value is coming from `std::get<N>(tuple)`, which can return whatever it wants. See https://godbolt.org/z/bGq9d5MMa.
> 
> This might complicate things, as for arrays and structs the lifetime of the bound field depends on the lifetime of the source, but for tuples it might not be the case. For example if you deallocate the struct, the created `auto&` bindings are dangling, but for tuple-like types they might still be valid (e.g.: you don't return a reference to an internal field, but to a static/global variable).

I totally agree that this should be implemented and after our monday syn meeting I have digged into this! We agreed on doing changes in a follow up PR here https://github.com/llvm/llvm-project/pull/209278#discussion_r3578324752 and I think your requested change should be also part of that PR. 

I will add it to the project board, so we do not lose track of this!

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


More information about the cfe-commits mailing list