25.12 Example: A Bug Miri Might Catch

Consider a function that returns a pointer to a local variable:

fn return_dangling_pointer() -> *const i32 {
    let x = 10;
    &x as *const i32
}

fn main() {
    let ptr = return_dangling_pointer();
    unsafe {
        // Danger: 'x' is out of scope, so dereferencing 'ptr' is undefined behavior.
        println!("Value is {}", *ptr);
    }
}

Although this code might occasionally print 10 and appear to work, it exhibits undefined behavior. The pointer refers to memory that is no longer valid. Tools like Miri can detect this mistake before it leads to more serious problems.