FAQ - Help and questions

Does Rust have a garbage collector? How is memory freed?

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

Short answer

No. Rust has no garbage collector. Every value has one owner, and the value is freed at the end of the owner's scope, when the compiler inserts a call to its Drop code. Shared ownership uses reference counting through Rc or Arc, which frees the value when the last owner is gone.

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#

Rust frees memory deterministically, at a point you can read in the source. When a variable goes out of scope, the compiler inserts the code that destroys its value (the Drop trait). No background collector runs, there are no pauses, and the program does not carry a runtime for it.

Because every value has one owner, the compiler knows where each value ends. Moving a value to another variable or into a function moves the responsibility to free it with it. The output of this program shows the order, in the order the values are dropped:

src/main.rsrust
struct Guard(&'static str);

impl Drop for Guard {
    fn drop(&mut self) {
        println!("freeing {}", self.0);
    }
}

fn main() {
    let _a = Guard("a");
    {
        let _b = Guard("b");
        println!("inner scope ends");
    }
    let c = Guard("c");
    drop(c);
    println!("main ends");
}
text
inner scope ends
freeing b
freeing c
main ends
freeing a

b is freed at the closing brace of its block, c at the explicit drop(c), and a at the end of main. Memory held by a Vec, String or Box is freed the same way, and so are files, sockets and locks: Drop is the general "clean up when the owner is gone" mechanism, not only for memory.

How shared ownership works#

When several parts of a program really need to own the same value, wrap it in a reference-counted pointer. Rc is for one thread, Arc for values shared between threads. The value is freed when the last owner is dropped.

TypeThreadsCostFrees the value
Box<T>one ownerone allocationwhen the owner goes out of scope
Rc<T>single threada counter increment per clonewhen the count reaches zero
Arc<T>many threadsan atomic counter increment per clonewhen the count reaches zero
rust
use std::rc::Rc;
use std::sync::Arc;
use std::thread;

fn main() {
    let shared = Rc::new(String::from("one owner or many"));
    let other = Rc::clone(&shared);
    println!("Rc count = {}", Rc::strong_count(&shared));
    drop(other);
    println!("Rc count = {}", Rc::strong_count(&shared));

    let data = Arc::new(vec![1, 2, 3]);
    let handle = {
        let data = Arc::clone(&data);
        thread::spawn(move || data.iter().sum::<i32>())
    };
    println!("sum from a thread = {}", handle.join().unwrap());
    println!("Arc count = {}", Arc::strong_count(&data));
}
text
Rc count = 2
Rc count = 1
sum from a thread = 6
Arc count = 1

Common mistakes#

  • Expecting drop order to match C++ destructors in every case. Local variables are dropped in reverse order of declaration; the fields of a struct are dropped in the order they are declared.
  • Using Rc when plain ownership or a reference would do. Reference counting is a tool for shared ownership, not the default.
  • Building a cycle of Rc pointers. The counts never reach zero and the memory is never freed: see "Can a Rust program leak memory?".

Does Rust need a runtime?#

No runtime is needed for memory management. A program that uses async needs an executor, such as Tokio, which is a library you add, not part of the language.

What does drop(x) do?#

It takes ownership of x and lets it go out of scope immediately, so its Drop code runs at that line instead of at the end of the block.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet