Is it possible to cause a memory leak in Rust?

Yes, leaking memory in Rust is as easy as calling the std::mem::forget function.

You can also leak memory if you create a cycle of shared references:

A cycle between Rc pointers will never be deallocated. For this reason, Weak is used to break cycles. For example, a tree could have strong Rc pointers from parent nodes to children, and Weak pointers from children back to their parents.

You can also use Box::leak to create a static reference, or Box::into_raw in an FFI situation.

Actually, in a system programming language, you need to be able to create a memory leak, otherwise, for example in an FFI case, your resource would be freed after being sent for use in another language.

All those examples show that a memory leak does not offend the memory safety guaranteed by Rust. However, it is safe to assume that in Rust, you do not have any memory leak, unless you do a very specific thing.

Also, note that if you adopt a loose definition of the memory leak, there are infinite ways to create one, for example, by adding some data in a container without releasing the unused one.

Leave a Comment