Question on lifetimes and raw pointers

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
    });

The memory still exists -- especially since it was just an integer, it will just have a location on the stack. However, it's completely invalid for you to read or write that address after the variable is out of scope. You might be clobbering something else that codegen decided to use that space for.

2 Likes