Will it lead to memory leak?


#1

I’m new to rust. I wonder if it will lead to memory leak.

let mut x  = Box::new(1);
x = Box::new(2);

#2

No.

let mut x  = Box::new(1);   // x holds the ownership of the Box
x = Box::new(2);   // x assigned to other value, so the previous box is dropped

#3

For completeness sake, the example you provided will not leak but it is important to be aware that it is still possible to create memory leaks in Rust. E.g. with reference cycles or improperly implementing a destructor like Drop.

e: I forgot to add a relevant link to the nomicon.


#4

The code that actually runs is like:

let mut x = Box::new(1);
drop(x); 
x = Box::new(2);
drop(x);

#5

Thanks a lot.