rust - Stack behavior when returning a pointer to local variable -
i have simple example behaviour of rust not match mental image, wondering missing:
fn make_local_int_ptr() -> *const i32 { let = 3; &a } fn main() { let my_ptr = make_local_int_ptr(); println!("{}", unsafe { *my_ptr } ); } result:
3 this not expect. using notation given in the stack , heap
i expect stack frame this:
address | name | value ----------------------- 0 | | 3 inside make_local_int_ptr(), after line,
let my_ptr = make_local_int_ptr(); since a goes out of scope, expect stack cleared. apparently not.
furthermore, if define variable between creating my_ptr , printing dereferenced value of it:
fn main() { let my_ptr = make_local_int_ptr(); let b = 6; println!("{}", b); // have use b otherwise rust // compiler ignores (i think) println!("{}", unsafe { *my_ptr } ); } my output is:
6 0 which again not expected, thinking:
address | name | value ----------------------- 0 | b | 6 in case output be:
6 6 or (in c++ , go getting result):
address | name | value ----------------------- 1 | b | 6 0 | | 3 in case output be:
6 3 but why getting output getting?
also, why returning pointer local variable allowed? variable goes out of scope, , value pointer pointing becomes unpredictable.
you shouldn't returning pointer local stack variable @ all. doing undefined behaviour, , compiler free whatever wants.
when unsafe, promising compiler manually uphold of expected invariants... , breaking promise.
to put bluntly: you're violating memory safety, bets off. solution not that.
to explain why might seeing behaviour, (again, undefined behaviour, nothing guaranteed): stack isn't "cleared" in sense overwritten zeroes; it's not valid read longer.
also, because call make_local_int_ptr finished, compiler has no reason preserve stack space, can re-use space anything. 0 possibly due call println!?
Comments
Post a Comment