FAQ - Help and questions

Can a Rust program leak memory?

#memory#basics#ownershippublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Yes. Safe Rust rules out use-after-free and data races, but it does not promise that all memory is freed. Reference cycles built with Rc, values handed to Box::leak or mem::forget, and collections that only grow all keep memory alive. A Weak pointer breaks a cycle.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Leaking memory is not a memory-safety violation, so the compiler does not forbid it. The guarantees of safe Rust are that you cannot read freed memory, write out of bounds, or race on data. A program that holds on to memory it no longer needs is still correct in that sense, and Rust's standard library explicitly allows it (std::mem::forget and Box::leak are safe functions).

The leaks you meet in practice come in three kinds:

  1. Reference cycles. With Rc (or Arc), two values that own each other keep each other's count above zero forever.
  2. Deliberate leaks. Box::leak turns an allocation into a &'static mut reference that is never freed. It is used on purpose for values that must live as long as the program, such as global configuration.
  3. Growth that never ends. A cache, a queue or a Vec that only receives items. This is a logic bug in any language.

How to do it: see a cycle and fix it with Weak#

This program makes a cycle of two values, and a parent/child tree where the child points back to its parent with a Weak pointer. Weak does not own the value, so it does not keep it alive.

src/main.rsrust
use std::cell::RefCell;
use std::rc::{Rc, Weak};

struct Leaky {
    name: &'static str,
    other: RefCell<Option<Rc<Leaky>>>,
}
impl Drop for Leaky {
    fn drop(&mut self) {
        println!("dropping {}", self.name);
    }
}

struct Node {
    name: &'static str,
    parent: RefCell<Weak<Node>>,
    children: RefCell<Vec<Rc<Node>>>,
}
impl Drop for Node {
    fn drop(&mut self) {
        println!("dropping {}", self.name);
    }
}

fn main() {
    {
        let a = Rc::new(Leaky { name: "a", other: RefCell::new(None) });
        let b = Rc::new(Leaky { name: "b", other: RefCell::new(Some(Rc::clone(&a))) });
        *a.other.borrow_mut() = Some(Rc::clone(&b));
        println!("cycle: a={} b={}", Rc::strong_count(&a), Rc::strong_count(&b));
    } // neither "dropping a" nor "dropping b" is printed: the counts never reach zero

    {
        let parent = Rc::new(Node { name: "parent", parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]) });
        let child = Rc::new(Node { name: "child", parent: RefCell::new(Weak::new()), children: RefCell::new(vec![]) });
        *child.parent.borrow_mut() = Rc::downgrade(&parent);
        parent.children.borrow_mut().push(Rc::clone(&child));
        println!("with Weak: parent strong={} weak={}", Rc::strong_count(&parent), Rc::weak_count(&parent));
    } // both are dropped here

    let kept: &'static mut Vec<u8> = Box::leak(Box::new(vec![0u8; 16]));
    println!("a deliberately leaked buffer of {} bytes", kept.len());
}
text
cycle: a=2 b=2
with Weak: parent strong=1 weak=1
dropping parent
dropping child
a deliberately leaked buffer of 16 bytes

The two Leaky values never print "dropping": that is the leak. The tree frees both nodes because the child's pointer to the parent is Weak.

Common mistakes#

  • Assuming "Rust has no leaks". It has no unsafe memory errors; leaks are possible.
  • Using Rc<RefCell<T>> for a graph or tree with back-pointers, without Weak for the back direction.
  • Treating a growing HashMap cache as harmless. Put a bound on it (a maximum size or an expiry).

How do I find a leak in a Rust program?#

Compare the process's memory over time with a tool for your platform, and add a Drop implementation that prints (as above) to see which values are never freed. A heap profiler such as the ones that work with any native program (Valgrind on Linux, Instruments on macOS) also works on Rust.

Is Box::leak safe to call?#

Yes, it is a safe function. It gives up the ability to free that allocation, and nothing else.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet