I was playing around with raw pointers to understand them a little bit better and wrote the code below trying to cause a segmentation fault or panic. For some reason that I'm still unable to understand the code compiles and runs. My understanding is that x
shoul've been dropped and therefore the first unsafe block should panic, but it doesn't. My first guess is that ptrw
points to the place in memory where x
was and its data is still there even though x was freed. Am I right?
let ptrw;
let ptrr;
{
let mut x = 5;
ptrw = &mut x as *mut i32;
ptrr = &x as *const i32;
}
unsafe {
*ptrw += 1;
}
println!("{}", unsafe {
*ptrr
});