# Stack vs heap memory

> Stack frames die when the call returns. Heap blocks live until you free them, or the runtime does.

Source: https://fullbytedeveloper.com/blog/stack-vs-heap-memory
Published here: 2026-11-20, updated 2026-12-03

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]:

```c
#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;
}
```

```bash
gcc -O0 -Wall -Wextra -o stack_heap_demo stack_heap_demo.c
./stack_heap_demo
```

Captured on this host (gcc 13.3.0, Linux x86_64):

```text
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 0x7fffe973f408
```

Sandbox 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.

<figure>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 280" role="img" aria-label="Dark diagram: left stack frame lists stack_a, stack_b, and a heap_a pointer; an arrow points to right heap blocks holding starred heap values that live until free or runtime reclaim, no people.">
  <defs>
    <marker id="stackHeapArrow" markerWidth="10" markerHeight="10" refX="8" refY="3" orient="auto">
      <path d="M0,0 L8,3 L0,6 Z" fill="#14b8a6"/>
    </marker>
  </defs>
  <rect x="0" y="0" width="720" height="280" rx="12" fill="#0b1f3a"/>
  <text x="24" y="36" fill="#f8fafc" font-family="ui-sans-serif, system-ui, sans-serif" font-size="16" font-weight="700">one process, two lifetimes</text>
  <rect x="24" y="56" width="280" height="180" rx="8" fill="#123052" stroke="#14b8a6" stroke-width="2"/>
  <text x="40" y="88" fill="#14b8a6" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">Stack frame (main)</text>
  <text x="40" y="120" fill="#f8fafc" font-family="ui-monospace, monospace" font-size="14">stack_a = 1</text>
  <text x="40" y="148" fill="#f8fafc" font-family="ui-monospace, monospace" font-size="14">stack_b = 2</text>
  <text x="40" y="176" fill="#f59e0b" font-family="ui-monospace, monospace" font-size="14">heap_a ptr</text>
  <text x="40" y="208" fill="#cbd5e1" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">dies when main returns</text>
  <path d="M312 176 H380" stroke="#14b8a6" stroke-width="3" fill="none" marker-end="url(#stackHeapArrow)"/>
  <rect x="388" y="56" width="308" height="180" rx="8" fill="#123052" stroke="#f59e0b" stroke-width="2"/>
  <text x="404" y="88" fill="#f59e0b" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">Heap blocks</text>
  <text x="404" y="120" fill="#f8fafc" font-family="ui-monospace, monospace" font-size="14">*heap_a = 10</text>
  <text x="404" y="148" fill="#f8fafc" font-family="ui-monospace, monospace" font-size="14">*heap_b = 20</text>
  <text x="404" y="184" fill="#cbd5e1" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">live until free() or runtime</text>
  <text x="404" y="212" fill="#cbd5e1" font-family="ui-sans-serif, system-ui, sans-serif" font-size="14">reclaim [1][3][4]</text>
</svg>
</figure>

*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].

```cpp
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](/blog/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](/blog/rust-lifetimes-plain) 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](/blog/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](https://fullbytedeveloper.com/blog/topic/dev-explainers).

Send this to the friend who nods along when someone says stack and heap but is not sure.

Image: Split dark-mode memory diagram: on the left a neat vertical stack of shrinking teal frames with the top frame dissolving, and on the right scattered amber heap blocks of uneven size linked by thin pointer threads that linger on the floor, with no typography.
https://fullbytedeveloper.com/media/stack-vs-heap-memory/stack-vs-heap-memory-venice.webp
Stack frames vanish when the call returns. Heap blocks live until something frees them.

## Sources

1. [Rust Book: What Is Ownership? (The Stack and the Heap), accessed 2026-11-20](https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html)
2. [Rust By Example: Box, heap allocation, accessed 2026-11-20](https://doc.rust-lang.org/stable/rust-by-example/std/box.html)
3. [Illinois CS 225: Stack and Heap Memory, accessed 2026-11-20](https://courses.grainger.illinois.edu/cs225/fa2021/resources/stack-heap/)
4. [Illinois Systems Encyclopedia: Basic Memory Management in C, accessed 2026-11-20](https://systems-encyclopedia.cs.illinois.edu/articles/c-memory-management/)
5. [Stanford CS106B: Dynamic Memory Management (archive), accessed 2026-11-20](https://web.stanford.edu/class/archive/cs/cs106b/cs106b.1242/lectures/16-dynamic-memory-management/)
6. [OpenStax Intro CS 6.4 Memory Management, accessed 2026-11-20](https://openstax.org/books/introduction-computer-science/pages/6-4-memory-management)
7. [OpenStax Intro CS 7.2 Programming Language Constructs, accessed 2026-11-20](https://openstax.org/books/introduction-computer-science/pages/7-2-programming-language-constructs)
8. [Discord Engineering: Using Rust to Scale Elixir for 11 Million Concurrent Users, accessed 2026-11-20](https://discord.com/blog/using-rust-to-scale-elixir-for-11-million-concurrent-users)
