Memory leaks are possible in safe Rust according to The Embedded Rust Book

I am going through The Embedded Rust Book and I ran into this paragraph in the Collections chapter.

OOM failures can be harder to debug than say unwrap -ing on all Result s returned by heapless::Vec.push because the observed location of failure may not match with the location of the cause of the problem. For example, even vec.reserve(1) can trigger an OOM if the allocator is nearly exhausted because some other collection was leaking memory (memory leaks are possible in safe Rust).

The last sentence threw me off. I assume this is a mistake but I'm not sure. Can someone explain what the book is trying to say? Is it true that memory leaks are possible in safe Rust?

Yes, memory leaks are possible in safe Rust, although they tend to be more difficult to trigger than in other languages.

For example, if you have two Rcs pointing at each other, they'll never be deallocated (which is why the Weak type exists).

1 Like

Yes, they are possible in safe Rust. It is generally impossible to fully prevent that without removing many useful tools such as reference counting. That said, cycles of reference counted objects are the only case where they are likely to happen accidentally.

1 Like

It is difficult to define "memory leak" in such a way that it is possible to completely eliminate them via static analysis. If you try you end up with still more unpleasant consequences like RefCell or Rc being unsound.

A long time ago (so to speak) there was a sort of general feeling that memory leaks should not be possible in safe code, and some APIs were designed around this assumption, such as the now-defunct std::thread::scoped. When this API was found to be unsound, the eventual outcome was what we have today: mem::forget was made safe, and thread::scoped was removed. If you want to learn more about the "Leakpocalypse", this blog post is a good place to start.

7 Likes

And that isn't even considering the types of "memory leaks" that happen in garbage collected languages, like in JavaScript when code continually appends to an array or map and never clears it.

The objects are still reachable. The program code just won't.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.