Memory, safety and Rust ownership · Part 25 of 36
Stack, heap and garbage collection
Expert 18 min
Where values live, how reference counting and tracing garbage collectors free memory, and what memory leaks look like in managed languages.
What you will learn
- You can explain stack and heap allocation.
- You can compare reference counting with tracing garbage collection.
- You can find and avoid memory leaks in JavaScript and Python.
Before this: Threads, data races and locks
Two regions
A running program uses two main memory regions for its data:
- The stack holds the local variables of each active function call in a frame. Calling a function pushes a frame; returning pops it. Allocation is just moving a pointer — extremely fast — but sizes must be known and data dies when the function returns.
- The heap holds data whose size or lifetime isn't fixed: lists that grow, objects shared between functions, strings read from a file. Allocation is slower, and somebody must free the memory when it is no longer needed.
In JavaScript and Python almost every value you create lives on the heap; your variables hold references to it.

Manual management
In C you call malloc and free yourself; in C++ you use new/delete or, better, smart pointers. Forgetting to free causes leaks; freeing too early causes use-after-free; freeing twice causes double free. The last two are security vulnerabilities (next lesson).
Reference counting
CPython stores a counter in every object: how many references point to it. When the count drops to zero, the object is freed immediately. Simple and predictable — but a cycle (a list that contains itself, two objects pointing at each other) never reaches zero. So CPython also runs a cycle collector (gc module) from time to time. Swift and Objective-C also use reference counting (ARC); Rust offers it on request with Rc/Arc.
Tracing garbage collection
JavaScript engines, Java, Go and .NET use tracing GC: starting from roots (global variables, the stack), the collector marks every object it can reach; everything unmarked is garbage. Modern collectors are:
- generational — most objects die young, so a small "young generation" is collected often and cheaply (V8 calls it the scavenger);
- incremental and concurrent — they do most of the work in small steps or on helper threads, keeping pauses short (V8's Orinoco, Java's ZGC with sub-millisecond pauses).
GC trades some CPU and memory overhead for safety and convenience: no use-after-free, no double free.
Leaks still happen
A GC frees what is unreachable, not what is unused. Typical leaks in managed languages:
- a cache (a
Map, adict) that only ever grows — bound it (LRU) or useWeakMap/weakref; - event listeners that are never removed and keep a whole component alive;
- closures that capture a large object by accident;
- global lists used for "debugging" that nobody empties.
Browser DevTools' memory panel (heap snapshots) and Python's tracemalloc show what keeps memory alive.
Value vs reference semantics
Whether an assignment copies data or shares it is a memory question too. In JavaScript and Python, numbers and strings behave like values (they are immutable), while arrays, objects, lists and dicts are shared by reference (lesson "Lists, dictionaries and objects"). Languages such as C, C++, Rust, Go and Swift let you choose — Rust makes that choice explicit through ownership.
Key points
- The stack holds call frames (fast, fixed lifetimes); the heap holds flexible data that must be freed.
- Manual freeing risks leaks, use-after-free and double free.
- CPython uses reference counting plus a cycle collector.
- JavaScript, Java and Go use generational, incremental tracing GCs with short pauses.
- GCs free unreachable data only; unbounded caches and listeners still leak.
Flashcards
- Question: Why is stack allocation fast?
- Answer: It only moves the stack pointer; frames are freed automatically on return.
- Question: Which problem does reference counting alone not solve?
- Answer: Reference cycles — they never reach a count of zero.
- Question: What does a tracing GC start from?
- Answer: The roots: globals and references on the stack.
- Question: Name a typical memory leak in JavaScript.
- Answer: An ever-growing cache or event listeners that are never removed.
Check yourself
Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.
Match the problem with its description.
Show the answer
Memory leak = Memory is never freed although unused; Use-after-free = Memory is used after it was freed; Double free = The same memory is freed twice
All three are typical of manual memory management.
Source: OSTEP, ch. 14 Memory API
Two Python objects reference each other and nothing else references them. What frees them?
- The cycle collector (gc)
- Reference counting alone
- Nothing — they leak forever
- The operating system immediately
Show the answer
The cycle collector (gc)
Their counts never reach zero, so CPython’s cycle collector finds and frees them.
Source: Python docs, gc
Why are generational collectors efficient?
- Most objects die young, so collecting a small young area often is cheap
- They never pause the program
- They use reference counting
- They free memory at compile time
Show the answer
Most objects die young, so collecting a small young area often is cheap
The weak generational hypothesis: most objects are short-lived.
Source: V8 blog, Trash talk
Which can cause leaks even with a garbage collector?
- An unbounded cache Map
- Event listeners that are never removed
- A local variable in a function that returned
- A global list that keeps growing
Show the answer
An unbounded cache Map; Event listeners that are never removed; A global list that keeps growing
Reachable but unused data is never collected; a finished function’s locals become unreachable.
Source: V8 blog, Trash talk / MDN Memory management
Sources
- Operating Systems: Three Easy Pieces, ch. 13–17 Memory, Arpaci-Dusseau, 2023
- Python documentation: gc — Garbage Collector interface, Python Software Foundation, 2025
- V8 blog: Trash talk — the Orinoco garbage collector, V8 team, 2019
Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.