Lint for returning a pointer to stack memory associated with a local variable
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Code
pub fn foo() -> *const i32 {
let x = 42;
&x
}
Current output
rustc doesn't currently warn about this.
Desired output
A warning that this pointer is referencing a local variable and is going to be dangling immediately. E.g.
error: returning a pointer to stack memory associated with a local variable
--> <source>:12:5
|
LL| &x
| ^^
Rationale and extra context
This code is very unlikely to be correct, which is exactly why a warning should be emitted. This would be similar to Clang's -Wreturn-stack-address warning.
In case of returning a reference, rustc would catch this and emit a compiler error. While it is fine to create such a pointer, it is very unlikely that the code should be written that way.
Rust Version
rustc 1.84.0-nightly (b8c8287a2 2024-11-03)
binary: rustc
commit-hash: b8c8287a229cd79604aa84c25e1235fc78cd5f2e
commit-date: 2024-11-03
host: x86_64-unknown-linux-gnu
release: 1.84.0-nightly
LLVM version: 19.1.3
Anything else?
If this becomes a Warn lint it will start warning immediately and potentially break users that configured warnings as errors. So maybe this should be Allow for the beginning?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the Rust example and examining the compiler's existing raw-pointer and dangling-reference diagnostics. Trace the lint implementation and its UI-test conventions, using Clang's -Wreturn-stack-address behavior as context. Done means the example produces the requested diagnostic with an appropriate initial lint level, without warning on ordinary raw-pointer creation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100