I'm playing with unsafe rust and trying to implement and I've found something I don't understand. I thought for sure I'd have a dangling pointer and that I'd get some kind of runtime error when trying to run this, but I don't.
fn main() {
let s1 = String::from("s1");
let s1_raw_ptr: *const String = &s1;
drop(s1);
unsafe {
let s = &*s1_raw_ptr;
println!("s recovered from raw pointer: {:?}", s);
}
}
This outputs:
s recovered from raw pointer: "s1"
I thought that when a value goes out of scope in Rust that it is immediately cleaned up. How is it that dereferencing a raw pointer to a now-dropped value is working?