I have a simple example where the behaviour of Rust does not match my mental image, so I am wondering what am I missing:
fn make_local_int_ptr() -> *const
You shouldn't be returning a pointer to a local stack variable at all. Doing so is undefined behaviour, and the compiler is completely free to do whatever it wants.
When you say unsafe
, you are promising the compiler that you will manually uphold all of its expected invariants... and then immediately breaking that promise.
To put it bluntly: you're violating memory safety, all bets are off. The solution is to not do that.
To explain why you might be seeing this behaviour, however (again, this is undefined behaviour, nothing is guaranteed): the stack isn't "cleared" in the sense that its overwritten with zeroes; it's just not valid to read from it any longer.
Also, because the call to make_local_int_ptr
is finished, the compiler has no reason to preserve its stack space, so it can re-use the space for anything. The 0
is possibly due to the call to println!
?