5

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.

Babur Makhmudov
  • 307
  • 1
  • 8
  • 2
    The [nomicon](https://doc.rust-lang.org/nomicon/drop-flags.html) might be interesting to you. – SOFe Aug 11 '19 at 17:04

1 Answers1

7

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.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • Thank you for your reply, could you point me to official documentation, where I can read more about this, if there's any? – Babur Makhmudov Aug 11 '19 at 15:57
  • 2
    @Babur: Take a look at https://doc.rust-lang.org/std/ops/trait.Drop.html and the linked part of the rust book – msrd0 Aug 11 '19 at 18:34