You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
0 commit comments