Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who is responsible to free the memory after consuming the box

Tags:

rust

From the Rust docs.

The into_raw function consumes a box and returns the raw pointer. It doesn't destroy T or deallocate any memory.

in this code:

fn main() {
    let b = Box::new("hello".to_owned());
    let a: *mut String = Box::into_raw(b);
}

I was not using unsafe block and as result we should have no memory leaks. So, if Box object is not responsible to free the memory after it was consumed, but the memory is not freed and available for further using, and raw pointers don't own by resources, who will free the memory?

like image 632
Oleh Devua Avatar asked Sep 14 '25 18:09

Oleh Devua


2 Answers

https://doc.rust-lang.org/stable/std/boxed/struct.Box.html#method.into_raw specifies: "After call to this function, caller is responsible for the memory previously managed by Box, in particular caller should properly destroy T and release memory. The proper way to do it is to convert pointer back to Box with Box::from_raw function, because Box does not specify, how memory is allocated."

So if you let your raw pointer go out of scobe without converting it back to a box, you have a memory leak.

like image 186
Rasmus Kaj Avatar answered Sep 17 '25 18:09

Rasmus Kaj


Disclaimer: pointed out by @fjh in comments, but worth mentioning.

Memory safety is not well-defined in general, thus a specific definition was established for Rust. The gist of it is that memory safety, for Rust, means: only accessing allocated and initialized memory.

A consequence of this definition is that memory leaks are safe because they cannot lead to dangling pointers. It is also considered safe not to run destructors, because they cannot violate memory safety (although this can leak other resources).

  • std::mem::forget was made stable by this RFC
  • it has always been possible to leak, using cycles of std::rc::Rc or std::sync::Arc
  • ...

Box::into_raw is mainly for interaction with FFI, so as to be able to transfer ownership across language boundaries, as is mentioned in its documentation the proper way to release the memory is to use Box::from_raw to recreate a Box from it.

like image 22
Matthieu M. Avatar answered Sep 17 '25 19:09

Matthieu M.