Memory leaks in Rust


#1

I’m new to Rust. After facing some memory leaks in C/C++, I was wondering if there are memory leaks in Rust. If it does, can you provide a simple example?

Furthermore, how rust handels with memory leaks?
I read that Rust handles with ‘dangling references’ by using the lifetime feature, is there something similar in Rust? mayabe a Garbage collector?


#2

Have a read of the Rust book; the memory management overview is here.


#3

Rust does not prevent memory leaks. It encourages RAII, much like good C++, and additionally does have the borrow checker to make sure that references can’t outlive the object. But you can still leak with Rc loops or just calling mem::forget. Read more here:


#4

gc languages still suffer if the code object leaks. I believe semi-thoughtful use of Rc (i.e. what developers do) won’t be much worse than the typical thought put into preventing object leaks occurring.

Detection is the same as C.
env RUSTFLAGS="-Z sanitizer=leak" cargo +nightly run
or valgrind. Many tools tend to be compatible (to some extent) due to llvm backend.


#5

Memory management is really pleasant in Rust. It’s automatic and deterministic. In practice memory leaks are not a problem in Rust. I’ve written several large codebases and haven’t got a leak even once.

The ownership rules and lifetime annotations help Rust automatically and accurately insert calls to destructors at compile time. You have to structure your code to make the borrow checker happy, but then you can be as careless with not freeing memory as if it was JavaScript.

Leaks may happen, but generally only in specific situations:

  • when you share data with C/C++ and intentionally “leak” it to let C/C++ manage it,
  • if you use reference-counted smart pointers and create a cycle.

#6

This part of The Book shows how to create a reference cycle that leaks memory in Rust; it’s possible but difficult.