rust-lang / rust-lang/rust-clippy

returning pointer to local variable from its block

Open
#11,510 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

the borrow checker checks when a reference got out of its scope, but not for raw pointers, where thing might get weird.

for example:

fn local_ptr() -> *const i32 {
    let temp: i32 = 123;
    &temp as *const i32
}
fn main() {
    let p = local_ptr();
    unsafe {
        println!("{}", *p);
    }
}

The above code prints 0 (Because temp was allocated in the stack???), run it in playground.

I don't think there was anyway to help people avoid such code, if there is, please let me know.

Advantage
  • Help reducing undefined behaviors
Drawbacks

Might be hard to cover all the cases while not causing false positive results.

Example
fn local_ptr() -> *const i32 {
    let temp: i32 = 123;
    &temp as *const i32
}

Could be written as:

fn local_ptr() -> *const i32 {
    static temp: i32 = 123;
    &temp as *const i32
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Rust examples in the issue, especially local_ptr, and investigate how a Clippy lint could identify raw pointers derived from block-local variables. Done means the unsafe pattern is diagnosed while avoiding the false positives noted in the issue.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.