I wrote some Rust to examine how to return a Box<T> for later use which did what I thought, but then I wrote something I expected to be rejected by the compiler only to find it compiled and ran. It appears to leak memory:
fn main() {
// test data
let v: i32 = 5;
let w: i32 = 11;
let x: i32 = 32;
let mut p: Box<i32> = box_this(v);
println!("{:p} contains {}", p, p);
// mutate contents of p (*p)
*p += w;
println!("{:p} contains {}", p, p);
// Make p point to something else. Does the compiler know to free what p formerly pointed to??
p = box_this(x);
println!("{:p} contains {}", p, p);
}
fn box_this(val: i32) -> Box<i32> {
Box::<i32>::new(val)
}
output:
0x55c025781c00 contains 5
0x55c025781c00 contains 16 // what happens to this allocation?
0x55c025781d70 contains 32
When p = box_this(x) executes, does the compiler know to drop the allocation of Ox....1c00 as now nothing points to that, or does this actually orphan the chunk at that location? It would orphan if this was C and no free(p) was executed before a new p = malloc(...).
I realize this is unlikely to occur in a real program, because let p = box_this(some_val) would almost certainly be in the scope of a loop, and would dropped at the end of the loop.