Sub topic 1
Why ownership exists: stack, heap, and manual memory
Prerequisites
This chapter assumes you already know the following:
- Basic Rust syntax: variables, functions, structs, and enums.
- How to build and run a program with
cargo. - A general idea of what the stack and the heap are.
- Common types such as
String,Vec, and&str.
You do not need to know anything about ownership yet. This chapter explains the problem that ownership solves. The later chapters cover the rules themselves.
Two places to keep data
A running program stores values in two main regions of memory.
The stack holds the local variables of each active function call. Each call gets a frame. When the function returns, the frame is removed. Allocation and cleanup are just a move of one pointer, so the stack is very fast. The cost is a restriction: the compiler must know the size of every value at compile time, and the value cannot outlive its frame.
The heap holds data whose size is unknown at compile time, or data that must outlive the function that created it. To use it, the program asks an allocator for a block of a given size. The allocator returns a pointer. The program must later tell the allocator that the block is no longer needed. This is slower than the stack, and it leaves the program responsible for the block's lifetime.
| Property | Stack | Heap |
|---|---|---|
| Size known at compile time | Required | Not required |
| Allocation cost | Very low | Higher (allocator call) |
| Freed when | The function returns | Someone releases it |
| Access | Directly by variable | Through a pointer |
| Typical Rust types | `i32`, `bool`, `[u8; 4]`, `&str` (pointer and length) | Contents of `String`, `Vec<T>`, `Box<T>` |
A String shows how the two work together. The variable itself lives on the stack and holds three fields: a pointer, a length, and a capacity. The text bytes live on the heap, and the pointer refers to them.
The stack part is small and fixed in size. The heap part can grow. Everything that follows in this tutorial depends on this split: someone must be responsible for the heap block.
The problem of manual memory
In languages with manual memory management, such as C, the programmer pairs every allocation with a release. Here is the idea in C:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(void) {
char *p = malloc(6);
strcpy(p, "hello");
printf("%s\n", p);
free(p);
return 0;
}Nothing in the language checks that free is called, called once, or called before the last use of p. The compiler accepts the program whether or not you get this right. The result is a family of bugs.
- Memory leak: the block is never freed. The program keeps growing in memory use. A leak is not a memory-safety violation, but a long-running service can eventually run out of memory.
- Double free: the same block is freed twice. The allocator's internal bookkeeping becomes corrupt. This can crash the program, and in some cases attackers can exploit it.
- Use after free: the program reads or writes through a pointer after the block was freed. The memory may now belong to something else, so the program reads wrong data or overwrites unrelated data.
- Dangling pointer: any pointer that refers to memory that is no longer valid. Use after free is the act of using one. A pointer to a stack variable that was returned from a function is a common source.
char *make_greeting(void) {
char buf[6] = "hello";
return buf; /* buf lives in this stack frame, which is gone after return */
}Most C compilers warn about this one, but the language does not forbid it.
Two common alternatives
Language designers have mostly picked one of two ways to avoid these bugs.
Garbage collection (Java, Go, Python, C#) adds a runtime component that finds blocks no longer reachable and frees them. This removes the three bugs above. The trade-offs are runtime overhead, less predictable pause times, and extra memory use. Garbage collection also manages only memory. Files, sockets, and locks still need explicit handling, such as try-with-resources or defer.
Reference counting (used by Swift and, optionally, C++ shared_ptr) keeps a count of users on each block and frees it when the count reaches zero. It is predictable, but every copy and drop updates a counter, and cycles leak.
Rust takes a third approach: the compiler decides when to free memory, using rules about who owns each value. The decision is made at compile time, so there is no collector and no counter by default.
What Rust does instead
The core idea is that every value has exactly one owner, and the owner is responsible for the value's cleanup. When the owner goes out of scope, the compiler inserts the cleanup call at that point. You never write free.
fn main() {
let s = String::from("hello");
println!("{s}");
} // s goes out of scope here; its heap block is freed automaticallyThis design addresses each manual-memory bug:
| Bug | How Rust prevents it |
|---|---|
| Leak (forgetting to free) | The owner's scope ends, so cleanup is inserted automatically |
| Double free | There is one owner, so cleanup runs once |
| Use after free | The compiler rejects use of a value after it was moved or its owner is gone |
| Dangling pointer | References cannot outlive the value they point to |
Two details deserve care.
First, "leak" is not fully excluded. Safe Rust can still leak memory, for example with std::mem::forget or with reference cycles using Rc. Rust guarantees memory safety, not the absence of leaks. Later chapters return to this.
Second, the checks happen at compile time and have no runtime cost in the ordinary case. The price is paid by the programmer, who must learn to write code the compiler can verify. Programs that would be fine in C, or in a garbage-collected language, are sometimes rejected because the compiler cannot prove them safe. Most of the rest of this tutorial is about understanding why a program is rejected and how to restructure it.
Why a single owner is enough
Consider why one owner is the right rule. Cleanup must happen exactly once. If two variables each believed they owned a block, both would free it, which is a double free. If zero variables owned it, nobody would free it, which is a leak. Exactly one owner gives exactly one cleanup.
The simplest model of this would make every assignment copy the heap data too. That would be safe but slow. Rust instead lets ownership move from one variable to another without copying the heap block, and lets code borrow a value temporarily through references. The remaining chapters build that system in order:
- The ownership rules and scope-based cleanup.
- Moves,
Copy, andClone. - Ownership across function calls.
- Shared and mutable references, and the borrow checker.
- Slices, dangling references, and lifetimes.
- Standard-library types (
Box,Rc,RefCell,Arc,Mutex) for cases where one owner is too strict.
Seeing the difference in code
The stack and heap split is visible in ordinary Rust. This program prints the size of the stack part of several types. The size of a String variable does not depend on how much text it holds.
use std::mem::size_of_val;
fn main() {
let n: i32 = 42;
let short = String::from("hi");
let long = String::from("a much longer piece of text than the first one");
println!("i32: {} bytes", size_of_val(&n));
println!("short String: {} bytes on the stack", size_of_val(&short));
println!("long String: {} bytes on the stack", size_of_val(&long));
println!("short heap bytes: {}", short.len());
println!("long heap bytes: {}", long.len());
}On a 64-bit platform, both String values report 24 bytes on the stack: three machine words for pointer, length, and capacity. The heap sizes are 2 and 46 bytes. The stack size is fixed, so the compiler can lay out the frame in advance, while the heap block is sized at run time.
Common misconceptions
- "Ownership is only about heap memory." The rules apply to all values, though they matter most for types that manage a resource. Types such as
FileandMutexGuardalso use ownership to release non-memory resources. - "Rust has a hidden garbage collector." It does not. Cleanup calls are inserted at compile time at the end of each owner's scope.
- "Ownership means I must copy data a lot." Moves and borrows avoid copies in most cases.
- "A compile error means my idea is wrong." Often the idea is fine and the code needs a different shape, such as a borrow instead of a move.
Exercise
A C function allocates a buffer with malloc, stores the pointer in two different variables, and then calls free on both. Name the bug. Then explain which Rust rule makes the equivalent situation impossible to write in safe code.
Show answer
This is a double free. In Rust, every value has exactly one owner, and cleanup runs once when that owner goes out of scope. Assigning a String to a second variable moves ownership, and the first variable can no longer be used, so two variables cannot both free the same block.
Exercise
A String named s holds the text "hello". Which parts of it live on the stack, and which on the heap? How many bytes does the stack part take on a 64-bit platform, and does that number change if the text grows to 1000 bytes?
Show answer
The pointer, length, and capacity live on the stack. The text bytes live on the heap. The stack part takes 24 bytes (three 8-byte words) and does not change when the text grows. Only the heap block grows.