0

I wrote some Rust to examine how to return a Box<T> for later use which did what I thought, but then I wrote something I expected to be rejected by the compiler only to find it compiled and ran. It appears to leak memory:

fn main() {
    //  test data
    let v: i32 = 5;
    let w: i32 = 11;
    let x: i32 = 32;

    let mut p: Box<i32> = box_this(v);
    println!("{:p} contains {}", p, p);

    //  mutate contents of p (*p)
    *p += w;
    println!("{:p} contains {}", p, p);

    //  Make p point to something else.  Does the compiler know to free what p formerly pointed to??
    p = box_this(x);
    println!("{:p} contains {}", p, p);
}

fn box_this(val: i32) -> Box<i32> {
    Box::<i32>::new(val)
}

output:

0x55c025781c00 contains 5
0x55c025781c00 contains 16  // what happens to this allocation?
0x55c025781d70 contains 32

When p = box_this(x) executes, does the compiler know to drop the allocation of Ox....1c00 as now nothing points to that, or does this actually orphan the chunk at that location? It would orphan if this was C and no free(p) was executed before a new p = malloc(...).

I realize this is unlikely to occur in a real program, because let p = box_this(some_val) would almost certainly be in the scope of a loop, and would dropped at the end of the loop.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
NateB
  • 509
  • 1
  • 3
  • 9
  • 2
    If you speak C++, you can think of `Box` as the Rust equivalent of `std::unique_ptr`. Just as assigning a different pointer to a `unique_ptr` won't leak in C++, neither will assigning a different box in Rust. – user4815162342 Sep 14 '20 at 15:11
  • 1
    Though the mechanisms how this works are very different in C++ and Rust. In C++, you need to explicitly implement `operator=()` to release the memory of the old pointer before assigning, in addition to implementing a destructor that also realeases the memory. In Rust, you only implement the `Drop` trait, and the compiler figures out all the places where it needs to be called, including upon reassignment. – Sven Marnach Sep 14 '20 at 18:57
  • 2
    It's rather difficult to _accidentally_ leak memory in Rust. – Sven Marnach Sep 14 '20 at 18:58
  • Thanks all, especially @Shepmaster for answer in the other post, that totally explains what is happening. – NateB Sep 14 '20 at 23:00

0 Answers0