Skip to main content
๐Ÿ“œ WAYPOINT LESSON

Stack vs Heap

โญ beginnerโณ 13 min read๐Ÿ“ Lesson 45 of 225

Two memories, two lifetimes: automatic locals vs allocations you control.

The stack: automatic and fast

Function locals live on the stack. When the function returns, that memory is reclaimed automatically:

void f(void) {
    int a[100];        // lives until f returns
}                      // gone โ€” no cleanup code written by you

Fast, but two limits: the size must be known at compile time, and the memory dies with the function.

The heap: manual and flexible

The heap holds memory you request at runtime with malloc and release yourself with free:

#include <stdlib.h>

int *p = malloc(10 * sizeof(int));   // ask for room for 10 ints
// ... p stays valid across function boundaries ...
free(p);                             // YOU give it back

Heap memory survives until you free it โ€” it can outlive the function that created it.

The one rule that follows you forever

If you allocated it, you own it: someone must free it exactly once.

  • forget to free โ†’ memory leak
  • free twice โ†’ undefined behavior (heap corruption)
  • use after free โ†’ undefined behavior

Modules ahead (file I/O, data structures) build directly on this rule.