Hacker News new | ask | show | jobs
by Rusky 3344 days ago
Rust doesn't guarantee no memory leaks any more than C++.
2 comments

While it is not part of the memory safety guarantee of safe Rust, in practice it is much harder to accidentally leak memory in Rust than in C++. There is no counterpart to the C++ new operator in Rust; no commonly-used language feature or standard library function puts the burden of explicitly freeing memory on the programmer.

For those who are interested in why leaking memory isn't disallowed by Rusts safety guarantees, have a look at the documentation of the (AFAIK) only safe function in the standard library that leaks memory: https://doc.rust-lang.org/std/mem/fn.forget.html

Actually... the counterpart to the C++ new operator would be the perfectly safe `Box::into_raw(Box::new(whatever))` - along with its counterparts on other smart pointer types - and there may be a heap module one day[0] - but your point stands that this is not the "default" way of allocating.

[0] https://doc.rust-lang.org/alloc/heap/

it actually does in a certain way. if at some point the lone pointer ("pointer") to that memory goes out of scope then the memory is deallocated. happens a lot.
I'm well aware of that. Safe Rust, however, allows you to put that pointer in an Rc cycle, or call mem::forget on it, etc.