Would reassigning a box in rust leak memory?

Would reassigning to a box leak memory?

fn main() {
    let mut x: Box<i32> = Box::new(1);
    for i in 1..(Insert large number here) {
        x = Box::new(i);
    }
}

No.

In general, Rust is designed around saving the programmer from having to think about memory management bugs. The language will almost always do the right thing by default. You can leak memory, but it's not trivial (e.g. it's either explicit via Box::leak(), etc., or you have to create circular structures involving Rc/Arc or some other, well-recognized construct, that you know will have the potential to leak memory.)

4 Likes

Reassigning to let mut x will drop (= run the destructor for) the value that it previously held, which in this case means deallocating the box.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.