Stack vs heap memory
Stack frames die when the call returns. Heap blocks live until you free them, or the runtime does.
Published here , updated · 8 sources · Resume reading
The stack holds each function call's locals in last-in, first-out order and frees them when the call returns. The heap holds blocks you allocate for longer or unknown-sized data; you (or the language runtime) free them later. A pointer to heap data can live on the stack while the bytes live elsewhere [1][3].
Quick start: print stack locals next to malloc blocks
Compile and run this C demo with optimizations off so addresses stay easy to teach [4]:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int stack_a = 1;
int stack_b = 2;
int *heap_a = malloc(sizeof(int));
int *heap_b = malloc(sizeof(int));
if (!heap_a || !heap_b) {
fprintf(stderr, "malloc failed\n");
return 1;
}
*heap_a = 10;
*heap_b = 20;
printf("stack_a addr=%p value=%d\n", (void *)&stack_a, stack_a);
printf("stack_b addr=%p value=%d\n", (void *)&stack_b, stack_b);
printf("heap_a addr=%p value=%d\n", (void *)heap_a, *heap_a);
printf("heap_b addr=%p value=%d\n", (void *)heap_b, *heap_b);
printf("pointer heap_a lives at %p\n", (void *)&heap_a);
free(heap_a);
free(heap_b);
return 0;
}gcc -O0 -Wall -Wextra -o stack_heap_demo stack_heap_demo.c
./stack_heap_demoCaptured on this host (gcc 13.3.0, Linux x86_64):
stack_a addr=0x7fffe973f400 value=1
stack_b addr=0x7fffe973f404 value=2
heap_a addr=0x55e14f9182a0 value=10
heap_b addr=0x55e14f9182c0 value=20
pointer heap_a lives at 0x7fffe973f408Sandbox capture on the review host; re-run on your box before you treat the numbers as a lab result.
Teaching points from this run only: stack_a and stack_b sit next to each other; heap payloads sit in a different address range; the pointer variable &heap_a itself lives with the other stack locals. Absolute hex values change per run and OS. Do not treat them as universal constants.
Left stack frame holds locals and the heap_a pointer. An arrow reaches right-side heap blocks with the starred values. Those payloads live until free or the runtime reclaims them; the frame dies when the call returns.
Name the lifetimes without inventing crash theater
Rust Book: the stack is LIFO; stack data needs a known fixed size; growing or unknown-size data goes on the heap; allocating returns a pointer that can sit on the stack while the payload sits on the heap [1]. Illinois CS 225: locals are automatic; after a function returns, its stack memory is deallocated and those locals are invalid [3]. OpenStax: if X calls Y, Y returns before X (call-stack LIFO) [6][7].
C: malloc / calloc / realloc allocate dynamic memory that exists until free. Globals and static storage last for the whole run [4]. C++ course notes: for every new, a matching delete (and array forms stay paired) [3][5].
int* p = new int;
delete p;
p = nullptr;Do not keep a pointer to a stack local after return. CS 225 walks that trap as teaching; prefer return-by-value or heap allocation when the object must outlive the function [3]. Exact crash versus silent wrong answer after misuse is undefined behavior territory for Part 2, not a promise on this page.
Keep the process picture and the name collision honest
Common teaching layout (CS 225, OpenStax): code and data toward low addresses, heap growing up, stack toward high addresses growing down [3][6]. Call that a common picture, not a law for every architecture.
OpenStax warning: the allocator "heap" is not a binary-tree heap structure. Free-block bookkeeping still gets called a heap in C and C++ [6].
Cross-language aside: Rust defaults to stack allocation; Box<T> puts a value on the heap [2]. Game and chat backends that moved hot paths into Rust often talk about ownership and allocation control in production writeups; Discord's engineering post on scaling with Rust is one public example of that motivation, not a stack-versus-heap tutorial [8]. CPython object bodies are heap-managed, so a Python "int on the stack" demo would mislead juniors here.
Mistakes worth correcting out loud
Returning &local from a C function and treating the address as still valid after return [3].
Calling every dynamic allocation a "binary heap" because of the shared English word [6].
Forgetting free (or delete) after malloc / new on a path that must stay leak-free in C or C++ [4][5].
Treating Python integers as C stack locals. Object payloads are heap-managed in CPython; use the C demo for the first mental model.
Turning off optimizations only for teaching, then shipping -O0 forever. The address layout lesson needs -O0; production builds do not.
Depth: who owns the free
In C you own the free. In Rust, ownership and Drop free heap data when the owner goes out of scope; Box<T> is the explicit heap handle [1][2]. In garbage-collected languages the runtime frees unreachable objects later. That is why Part 2 of this series (stack vs heap part 2: leaks) talks about retaining references too long, not only about forgetting free.
When Rust lifetimes show up in error messages, they name how long a reference may exist, not which region holds the bytes. Pair this page with Rust lifetimes in plain words when the question is borrow duration rather than placement.
Walk one call frame by hand
Imagine main calls helper. helper pushes a frame, stores locals, maybe mallocs a block, then returns. The frame is gone; the malloc block is still there if nobody freed it [3][4]. If helper returned a pointer to one of its locals, the caller now holds an address into recycled stack space. Prefer returning a value, or returning a heap pointer the caller must free.
That single story is enough to read most junior bug reports: "it worked until I returned," "it crashed only after the next call," "valgrind says invalid read on a local." The next call reused the stack slot; your dangling pointer still pointed at it.
What to try next
Re-run the demo and confirm stack addresses stay clustered while heap payloads stay in another range. Then open Part 2 for leaks and language differences. If someone asks whether Go or Rust is "faster because of the stack," separate placement from measured wall time with Is Go slower than Rust.
Size and growth without mythology
Stack frames want known, fixed-size locals. Grow a vector of unknown length and teaching materials send that storage to the heap [1][3]. That is why malloc takes a size argument and why Rust's Vec and String own heap buffers while a plain i32 can live on the stack. Recursion depth is a stack story: each call pushes another frame until the OS limit. A growing cache of responses is a heap story: the data outlives the function that fetched the first page.
Do not memorize every address from the demo. Memorize the lifetime rule. Stack storage ends with the frame. Heap storage ends when you free it, drop the owner, or the GC finds it unreachable [1][3][4].
Pointers are values too
In the captured run, &heap_a sat next to stack_a and stack_b. The pointer value is a stack local; the int it points at is a heap payload. Freeing the payload does not remove the pointer variable from the frame. Setting the pointer to NULL after free is a C hygiene habit so you do not double-free through a stale address [4][5]. Languages with ownership or GC hide that step; the underlying split remains useful when you read a crash dump.
Browse the Dev explainers topic.
Send this to the friend who nods along when someone says stack and heap but is not sure.

Keep this guide
Filed under Dev explainers
Questions about this guide
Is the allocator heap the same as a binary heap data structure?
No. OpenStax notes that C and C++ memory managers call the dynamic region a heap even though free blocks are not stored as a max-heap or min-heap tree. Keep the names separate.
Can I return a pointer to a local variable?
Do not. When the function returns, its stack frame is gone. The caller would hold a pointer into memory that is no longer valid for that local. Prefer return-by-value or allocate on the heap if the object must outlive the function.
Do Python ints live on the C stack?
Treat that as a no for this junior page. CPython manages object payloads on the heap. A C demo is the clearer first picture of stack locals versus malloc blocks.
Sources
- Rust By Example: Box, heap allocation, accessed 2026-11-20doc.rust-lang.org
- Illinois CS 225: Stack and Heap Memory, accessed 2026-11-20courses.grainger.illinois.edu
- Illinois Systems Encyclopedia: Basic Memory Management in C, accessed 2026-11-20systems-encyclopedia.cs.illinois.edu