Skip to content

returning pointer to local variable from its block #11510

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
J-ZhengLi opened this issue Sep 15, 2023 · 1 comment
Open

returning pointer to local variable from its block #11510

J-ZhengLi opened this issue Sep 15, 2023 · 1 comment
Labels
A-lint Area: New lints

Comments

@J-ZhengLi
Copy link
Member

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
}
@J-ZhengLi J-ZhengLi added the A-lint Area: New lints label Sep 15, 2023
@y21
Copy link
Member

y21 commented Sep 15, 2023

Looks similar to whats implemented in #10962.
Thats only for temporaries, but it might be that it already detects this because, as far as I know, at the MIR there isnt much of a distinction between &<val> as *const _ and x = <val>; &x as *const _ if no constant promotion or lifetime extension happens. I havent looked too much into detail how the lint is implemented though, so might be wrong.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

No branches or pull requests

2 participants