Memory Layout: Stack, Heap & Data in C
A running program's memory divides into segments with different rules: the stack holds locals and call frames (automatic, fast, limited — deep recursion or giant local arrays overflow it), the heap serves malloc (flexible, manual, fragmented), and data segments hold globals/statics (initialized .data vs zero-filled .bss) plus read-only text/constants.
Knowing the map diagnoses whole bug families: stack overflows from huge locals (move them static or heap), use-after-return from escaping addresses, and text-segment crashes from writing string literals. Size choices (stack array vs malloc) become architectural, not stylistic.
Stack: automatic and bounded
Locals and frames live here — typically megabytes total. Big local arrays and deep recursion are the classic overflow sources.
Heap: manual and vast
malloc territory — limited by RAM, managed by you, fragmented over time. Anything big or long-lived belongs here.
Data: globals and constants
Initialized globals in .data, zeroed ones in .bss, literals and code in read-only text — writing to text segfaults by design.
Choose deliberately
Small + short-lived → stack. Big, shared, or persistent → heap. Never return addresses of stack locals.
#include <stdio.h>#include <stdlib.h> int total = 0; int *make(void) { int *p = malloc(sizeof *p); if (p) *p = 7; return p;} int main(void) { int *v = make(); if (v) total = *v; printf("%d %d\n", total, (int)sizeof(int[1000])); free(v); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.