Search⌘ K
AI Features

Puzzle 12: Explanation

Explore Rust's approach to memory management by understanding why memory leaks occur without breaking safety guarantees. Learn how Rust's Drop trait and smart pointers automatically manage resources, and when deliberate memory leaks might be necessary, especially in interoperability scenarios. Discover how to balance Rust's safety features with practical memory control techniques.

Test it out

Hit “Run” to see the code’s output.

C++
fn main() {
loop {
let buffer = (0..1000).collect::<Vec<u32>>();
std::mem::forget(buffer);
print!(".");
}
}

Explanation

It is not surprising that the program runs endlessly since it will loop forever if there isn’t a break to stop it. The surprise comes when we let it run for a while as it eventually consumes all of our computer’s memory or is terminated by the operating system.

Allocating memory, losing the reference to it, and never cleaning up after ourselves can cause a memory leak. Equally surprising is that Rust generally makes us wrap violations of memory safety guarantees in unsafe tags. However, there are no unsafe tags shown in this example.

Rust makes strong, compiler-guaranteed promises regarding memory safety. Yet, surprisingly, memory leaks are not a violation of memory safety. In fact, Rust even provides std::mem::forget and Box::leak to let us explicitly cause a memory leak.

Are memory leaks safe?

The forget() function used to be marked as unsafe, but the Rust Core team decided that memory leaks fall outside of Rust’s memory protection guarantee. Rust Core team alumni Huon Wilson summarizes the language’s philosophy on ...