2
votes

In the following code, does the "box 5i" get properly freed when exiting the "main" scope? The wording on their pointer guide seems to indicate that variables with box types act as if there's an automatic "free()" call when the variable goes out of scope. However, if you "free()" on "a" in this code, it would only end up freeing the "box 8i" that is on the heap. What happens to the "box 5i" that "a" was originally pointing to?

fn foo(a: &mut Box<int>) {
    *a = box 8i;
}

fn main() {
    let mut a = box 5i;
    println!("{}", a); // -> "5"
    foo(&mut a);
    println!("{}", a); // -> "8"
}
1

1 Answers

4
votes

By default, overwriting a memory location will run the destructor of the old value. For Box<...> this involves running the destructor of the contents (which is nothing for an int) and freeing the allocation, so if a has type &mut Box<T>, *a = box value is equivalent to (in C):

T_destroy(**a);
free(*a);
*a = malloc(sizeof T);
**a = value;

In some sense, the answer to your question is yes, because the type system guarantees that *a = box ... can only work if a is the only reference to the old Box, but unlike most garbage collected/managed languages this is all determined statically, not dynamically (it is a direct consequence of ownership and linear/affine types).