C in 100 Seconds: Stack vs Heap — Where Variables Live
Video: C in 100 Seconds: Stack vs Heap — Where Variables Live | Episode 31 by Taught by Celeste AI - AI Coding Coach
Watch full page →Stack vs Heap
Every variable in C lives in one of two places: the stack or the heap. Understanding the difference is essential for writing safe, efficient code.
Stack Memory
Stack variables are automatic — declare them, use them, and they vanish when the scope ends:
Stack allocation is fast (just a pointer bump) but limited in size, and the data dies with the function.
The Dangling Pointer Problem
Returning the address of a stack variable creates a dangling pointer:
The compiler warns you: . The address exists, but the data behind it is already reclaimed.
Heap Memory
allocates memory on the heap that survives the function return:
The caller is responsible for calling when done.
When to Use Which
| Stack | Heap | |
|---|---|---|
| Speed | Fast (pointer bump) | Slower (allocator overhead) |
| Lifetime | Dies with scope | Lives until freed |
| Size | Limited (~1-8 MB) | Limited by RAM |
| Management | Automatic | Manual (malloc/free) |
Rule of thumb: Use the stack for short-lived data. Use the heap for data that must outlive the function that created it.
Student Code
Try it yourself: episode31/stackheap.c