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?
Have a read of the Rust book; the memory management overview is here.
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:
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.
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.
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.
This part of The Book shows how to create a reference cycle that leaks memory in Rust; it’s possible but difficult.