[clang] [LifetimeSafety] Track origins through array subscript and array-to-pointer decay (PR #186902)
Utkarsh Saxena via cfe-commits
cfe-commits at lists.llvm.org
Tue Mar 17 03:47:43 PDT 2026
================
@@ -1980,3 +1980,117 @@ void outer_pointer_outlives_inner_pointee() {
}
} // namespace LoopLocalPointers
+
+namespace array {
+
+void element_use_after_scope() {
+ int* p;
+ {
+ int a[10]{};
+ p = &a[2]; // expected-warning {{object whose reference is captured does not live long enough}}
+ } // expected-note {{destroyed here}}
+ (void)*p; // expected-note {{later used here}}
+}
+
+int* element_use_after_return() {
+ int a[10]{};
+ int* p = &a[0]; // expected-warning {{address of stack memory is returned later}}
+ return p; // expected-note {{returned here}}
+}
+
+void element_use_same_scope() {
+ int a[10]{};
+ int* p = &a[0];
+ (void)*p;
+}
+
+void element_reassigned_safe() {
+ int safe[10]{};
+ int* p;
+ {
+ int a[10]{};
+ p = &a[0];
+ }
+ p = &safe[0]; // rescued
+ (void)*p;
+}
+
+void multidimensional_use_after_scope() {
+ int* p;
+ {
+ int a[3][4]{};
+ p = &a[1][2]; // expected-warning {{object whose reference is captured does not live long enough}}
+ } // expected-note {{destroyed here}}
+ (void)*p; // expected-note {{later used here}}
+}
+
+void member_array_element_use_after_scope() {
+ struct S {
+ int arr[10];
+ int b;
+ };
+ int* p;
+ {
+ S s;
+ p = &s.arr[0]; // expected-warning {{object whose reference is captured does not live long enough}}
+ } // expected-note {{destroyed here}}
+ (void)*p; // expected-note {{later used here}}
+}
+
+void array_of_pointers_use_after_scope() {
+ int** p;
+ {
+ int x = 0;
----------------
usx95 wrote:
I would remove the smaller scope 'x' here as this test does not test it. Maybe just have this in the larger scope. `read_pointer_from_array_element_use_after_scope` better documents the smaller scope 'x' .
https://github.com/llvm/llvm-project/pull/186902
More information about the cfe-commits
mailing list