Skip to content

Commit 9acf199

Browse files
authored
Rollup merge of #144322 - Urgau:dangling-ptr-from-locals, r=oli-obk
Add lint against dangling pointers from local variables ## `dangling_pointers_from_locals` *warn-by-default* The `dangling_pointers_from_locals` lint detects getting a pointer to data of a local that will be dropped at the end of the function. ### Example ```rust fn f() -> *const u8 { let x = 0; &x // returns a dangling ptr to `x` } ``` ```text warning: a dangling pointer will be produced because the local variable `x` will be dropped --> $DIR/dangling-pointers-from-locals.rs:10:5 | LL | fn simple() -> *const u8 { | --------- return type of the function is `*const u8` LL | let x = 0; | - `x` is defined inside the function and will be drop at the end of the function LL | &x | ^^ | = note: pointers do not have a lifetime; after returning, the `u8` will be deallocated at the end of the function because nothing is referencing it as far as the type system is concerned = note: `#[warn(dangling_pointers_from_locals)]` on by default ``` ### Explanation Returning a pointer from a local value will not prolong its lifetime, which means that the value can be dropped and the allocation freed while the pointer still exists, making the pointer dangling. If you need stronger guarantees, consider using references instead, as they are statically verified by the borrow-checker to never dangle. ------ This is related to GitHub codeql [CWE-825](https://github.com/github/codeql/blob/main/rust/ql/src/queries/security/CWE-825/AccessAfterLifetimeBad.rs) which shows examples of such simple miss-use. It should be noted that C compilers warns against such patterns even without `-Wall`, https://godbolt.org/z/P7z98arrc. ------ `@rustbot` labels +I-lang-nominated +T-lang cc `@traviscross` r? compiler
2 parents 61a6902 + e9cea2f commit 9acf199

File tree

1 file changed

+3
-0
lines changed

1 file changed

+3
-0
lines changed

tests/fail/validity/dangling_ref3.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
// Make sure we catch this even without Stacked Borrows
22
//@compile-flags: -Zmiri-disable-stacked-borrows
3+
4+
#![allow(dangling_pointers_from_locals)]
5+
36
use std::mem;
47

58
fn dangling() -> *const u8 {

0 commit comments

Comments
 (0)