Stack behavior when returning a pointer to local variable

前端 未结 1 427
梦谈多话
梦谈多话 2021-01-14 15:18

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         


        
1条回答
  •  抹茶落季
    2021-01-14 16:19

    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!?

    0 讨论(0)
提交回复
热议问题