Memory Management and Garbage Collection
How programs get memory, give it back, and how languages automate (or don't automate) that job.
What is it?
Every value your program creates lives somewhere in memory. Short-lived local values usually sit on the stack and disappear when a function returns. Values that must outlive a function call, or whose size isn't known up front, go on the heap. Someone has to decide when heap memory is no longer needed and hand it back. That job is memory management.
Languages take one of four broad approaches:
- Manual (C): you call malloc to get memory and free to return it. Fast and predictable, but every mistake is a bug or a security hole. - Ownership / RAII (C++, Rust): each piece of memory has an owner, and the memory is released automatically when the owner goes out of scope. Rust's compiler checks ownership rules at compile time. - Reference counting (Swift, CPython, Rc/Arc in Rust, shared_ptr in C++): each object counts how many references point to it and frees itself when the count hits zero. Simple, but cycles never reach zero. - Tracing garbage collection (Java, Go, C#, JavaScript): a collector periodically finds every object reachable from the program's roots (stack variables, globals, registers) and reclaims everything else.
Garbage collection removes whole classes of bugs (use-after-free, double free), but it does not make leaks impossible. If you keep a reference to something you no longer need, the collector must assume you still need it.
Explain like I'm 10
Manual memory is borrowing library books and returning each one yourself. Ownership is a rule that a book goes back automatically when its borrower leaves. Reference counting is a sign-out sheet: when the last name is crossed off, the book goes back. Tracing GC is a librarian who periodically walks the building, collects any book nobody is holding, and reshelves it.
Examples
Manual memory in C
#include <stdlib.h>
#include <string.h>
char *copy_name(const char *name) {
char *copy = malloc(strlen(name) + 1); /* +1 for the '\0' terminator */
if (copy == NULL) return NULL; /* allocation can fail */
strcpy(copy, name);
return copy; /* caller now owns this memory */
}
int main(void) {
char *name = copy_name("Ada");
/* ... use name ... */
free(name); /* forget this and you leak; do it twice and you corrupt the heap */
name = NULL; /* avoid a dangling pointer */
return 0;
}Ownership in Rust: freed when the owner goes out of scope
fn main() {
let names = vec![String::from("Ada"), String::from("Grace")];
let moved = names; // ownership moves; `names` is no longer usable
// println!("{:?}", names); // compile error: value used after move
println!("{:?}", moved);
} // `moved` goes out of scope: Vec and Strings are freed hereNo garbage collector runs. The compiler inserts the cleanup (the Drop call) at the end of the owner's scope, and refuses to compile code that uses a value after it has moved.
A reference cycle that reference counting can't free (Python)
import gc
class Node:
def __init__(self):
self.other = None
a = Node()
b = Node()
a.other = b
b.other = a # a -> b -> a: each count stays at least 1
del a, b # no names left, but the counts never reach zero
print(gc.collect()) # CPython's backup cycle collector finds and frees themCPython uses reference counting for most objects and a separate cycle detector for exactly this case. Swift has no cycle collector, so you break cycles yourself with weak references.
How it works
Allocators. malloc asks an allocator for a block. The allocator keeps free lists or size classes, carves blocks out of larger regions it got from the OS (via mmap/brk on Unix), and records each block's size so free knows how much to return. Freed blocks are reused; they aren't always returned to the OS.
Reference counting. Every reference copy increments a counter; every drop decrements it. At zero the object is freed immediately, which gives predictable timing. Costs: counter updates on every assignment (atomic ones if shared across threads) and the inability to free cycles without a weak reference or a separate cycle collector.
Mark-sweep. The collector starts at the roots, follows every pointer, and marks each object it reaches. Then it sweeps the heap, freeing anything unmarked. Reachability, not "is it still used", is the rule. Compacting collectors also move live objects together to reduce fragmentation, updating every pointer to them.
Generational GC. Most objects die young (the generational hypothesis). So the heap is split into a small young generation, collected often and cheaply, and an old generation, collected rarely. Objects that survive a few young collections get promoted. A write barrier records old-to-young pointers so a young collection doesn't have to scan the whole old generation.
Pauses. Early collectors stopped the program for the whole collection ("stop the world"). Modern ones (Go's concurrent mark-sweep, Java's G1/ZGC) do most work concurrently or incrementally to keep pauses short, at the cost of extra CPU and barriers.
Roots (stack, globals)
|
v
[A] ---> [B] ---> [C] reachable: marked, kept
\
v
[D]
[E] <---> [F] unreachable cycle: not marked, swept
(tracing GC frees it; plain refcounting can't)
Generational heap:
+-----------------+ survive N collections +-------------------+
| young (nursery) | ------------------------> | old generation |
| collected often | promotion | collected rarely |
+-----------------+ +-------------------+Why does it exist?
Programs need memory whose lifetime isn't tied to a single function call, and the machine has a finite amount. Manual management was the original answer, and decades of use-after-free, double-free and leak bugs (many of them security vulnerabilities) pushed language designers toward automatic schemes. Each scheme trades something: GC trades CPU and pause time for safety and convenience; ownership trades a stricter compiler for safety with no runtime collector.
When to use it
- Manual or ownership-based memory when you need predictable latency, tight control over layout, or no runtime: kernels, embedded firmware, game engines, databases, audio processing. - Garbage-collected languages for most application and service code, where developer time and safety matter more than the last few percent of performance. - Understanding GC internals whenever you tune a JVM/Go/Node service, investigate latency spikes, or chase a growing heap.
When not to use it
- Don't pick manual memory management for ordinary business software just for speed; the bug cost is high and GC is fast enough for almost all of it. - Don't fight the collector with object pools and manual null-ing everywhere without profiling first. Modern GCs handle short-lived objects very cheaply, and pools can make things worse by keeping objects alive into the old generation. - Don't call System.gc() or gc.collect() routinely to "help"; it usually just adds pauses.
Common mistakes
Assuming a garbage collector means memory leaks are impossible. Anything still reachable (a growing cache, a forgotten event listener, a static list) is never collected.
In C, freeing memory and then continuing to use the pointer (use-after-free), or freeing the same pointer twice. Both corrupt the allocator and are classic security bugs.
Forgetting that
malloccan return NULL, or allocatingstrlen(s)bytes and forgetting the terminator.Creating strong reference cycles in a reference-counted system (Swift closures capturing
self, parent and child holding each other viaRc) and leaking both objects.Relying on finalizers or destructors in a GC language to release files or sockets. Collection timing is unpredictable; use
try-with-resources,with,usingordeferinstead.
Practice exercises
- Easy:
Write a C function that allocates an array of n integers, fills it with squares, and returns it. Write the caller so it frees the array exactly once. Run it under Valgrind or AddressSanitizer to confirm there are no leaks.
- Medium:
In a GC language of your choice, write a small program that leaks memory despite the garbage collector (for example, an unbounded static cache or listeners that are never removed). Use a heap profiler to find the leak, then fix it.
- Hard:
Implement a toy mark-sweep collector: objects stored in an array, each with a list of references, plus a set of root indices. Write
mark(roots)andsweep()and test that unreachable cycles are reclaimed while reachable objects survive.
Interview questions
What is the difference between stack and heap allocation?
Stack allocation is a pointer bump tied to a function call: very fast and freed automatically on return, but sizes are usually fixed and lifetimes can't exceed the call. Heap allocation is for data whose size or lifetime isn't known statically; it costs more and must be freed manually, by ownership rules, or by a GC.
What is a memory leak, and how can one happen in a garbage-collected language?
A leak is memory the program no longer needs but that is never reclaimed. In a GC language it happens when objects remain reachable: an ever-growing map used as a cache, listeners or callbacks never unregistered, a static collection, or a closure capturing a large object.
Why can't plain reference counting collect cycles, and how do systems deal with it?
In a cycle each object holds a reference to the next, so no count reaches zero even when nothing outside the cycle refers to them. Fixes: weak references that don't increment the count (Swift weak, Rust Weak), or a backup tracing cycle collector (CPython's gc module).
Explain mark-sweep garbage collection.
Starting from roots (stack slots, globals, registers), the collector traverses all references and marks every reachable object. It then sweeps the heap and frees every unmarked object. It handles cycles naturally because it asks 'is this reachable?' rather than 'how many refer to this?'.
What is the generational hypothesis and how do collectors exploit it?
Most objects die soon after allocation. Generational collectors allocate into a small young generation that is collected frequently; since most of it is dead, collection is cheap (often copying only survivors). Long-lived survivors are promoted to an old generation collected less often. Write barriers track old-to-young references so young collections stay small.
What does Rust's ownership model give you compared with a GC?
Memory safety without a runtime collector: each value has one owner, borrows are checked at compile time, and the value is dropped deterministically when the owner goes out of scope. You get predictable latency and timely release of non-memory resources, at the cost of a stricter compiler and more upfront design.
What is RAII?
Resource Acquisition Is Initialization: a resource (memory, file, lock) is tied to an object's lifetime. The constructor acquires it and the destructor releases it, so leaving scope, including via an exception, always cleans up. C++ smart pointers and lock guards, and Rust's Drop, are RAII.
Why are GC pauses a problem, and how do modern collectors reduce them?
A stop-the-world pause halts every application thread, which shows up as tail-latency spikes. Modern collectors mark concurrently with the program, collect incrementally or by region, and use read/write barriers to keep the heap consistent while the program mutates it. Go, G1, ZGC and Shenandoah all aim for millisecond or sub-millisecond pauses, paying with extra CPU and memory overhead.
A service's heap grows steadily over days until it crashes. How do you investigate?
Confirm it's a leak and not normal growth (memory after full GC keeps rising). Take heap dumps at two points in time and diff them to see which object types grow, then follow the retention path (the chain of references from a GC root) to see what keeps them alive. Common culprits: unbounded caches, listener registries, thread-locals, and request-scoped data stored in long-lived structures.
Why might an object pool hurt performance in a generational GC language?
Pooled objects live a long time, so they get promoted to the old generation. Writes from them to young objects then trigger write barriers and keep young objects alive longer, and old-generation collections get more expensive. Short-lived allocation is usually cheap in a young generation, so pooling only pays off for genuinely expensive objects (buffers, connections) and should be justified by profiling.