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 because x
is out of scope. Tools like Miri can detect this error before it leads to more severe problems.