What happens to heap allocated value after variabl

2020-04-10 01:22发布

I'm currently learning about Rust programming language, and after reading about ownership and lifetime concepts (which I find as an elegant alternative to GC), I cannot find an answer to the following question. As far as the ownership and lifetimes are concerned, the following code works as described with comments.

fn main() {
    let mut x: u32 = 10; // x is pointing to memory in stack
    println!("before reassignment: x = {}", x); // prints 10
    x = 11; // memory in stack simply has been updated with another value
    println!("after reassignment: x = {}", x); // prints 11
} // x is dropped here

everyone is happy, but imagine if we had a code like this:

fn main() {
    let mut x = Box::new([99; 1000]); // x owns a Box, which owns heap allocated array 
    println!("before reassignment: x[0] = {}", x[0]); 
    x = Box::new([100; 1000]); // x has been assigned another Box
    // what happened to previous heap allocated array, has it been
    // dropped behind the scenes, or is that a memory leak?
    println!("after reassignment: x[0] = {}", x[0]);
} // x is dropped here, only the last assigned value gets dropped with it.

What happens to heap allocated array (the one that was assigned first), does it live until the end of function, or will it be dropped at the moment of reassignment? I'm still learning Rust, so my understanding of memory management might be not complete.

The question is a little different than the one asked in When is the storage reclaimed for a resource that is no longer owned?, because it's about the case when owner-variable is still in scope, but simply has been assigned another value.

标签: rust
1条回答
混吃等死
2楼-- · 2020-04-10 01:42

Whenever you assign a new value to a variable of a type implementing Drop, the old value will be dropped before the new value is assigned. For a type owning heap-allocated memory like Box, this means the memory will be freed at the time of the assignment.

While it is possible to leak unreachable memory in safe Rust code, it is quite unlikely to happen by accident.

查看更多
登录 后发表回答