Skip to content

returning pointer to local variable from its block #11510

@J-ZhengLi

Description

@J-ZhengLi

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions