Rust places fixed-size data on the stack and dynamically sized data (like String contents) on the heap. Ownership tracks who frees heap allocations.
Stack vs heap
- Stack — fast LIFO; locals like
i32, pointers with known size - Heap — flexible size;
String,Vec,Boxallocate here
Compare with C++
Like C++, you control performance—but Rust's ownership prevents many manual memory bugs by default.
Important interview questions and answers
- Q: Where does a String's metadata live?
A: Stack struct pointing at heap buffer for UTF-8 bytes.
Self-check
- Which is faster to allocate: stack or heap?
- Who frees heap memory in safe Rust?