Learn C
#include "pointersmemory/memory_layout.h"

Memory Layout: Stack, Heap & Data in C

#concept

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.

#how it works
1

Stack: automatic and bounded

Locals and frames live here — typically megabytes total. Big local arrays and deep recursion are the classic overflow sources.

2

Heap: manual and vast

malloc territory — limited by RAM, managed by you, fragmented over time. Anything big or long-lived belongs here.

3

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.

4

Choose deliberately

Small + short-lived → stack. Big, shared, or persistent → heap. Never return addresses of stack locals.

#example
#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;
}
Output
7 4000
1total lives in the data segment (zero-initialized); make's heap int survives return, unlike a stack local would.
2The caller reads 7 through the returned heap pointer into the global total.
3sizeof(int[1000]) is 4000 bytes of would-be stack — illustrating why big arrays belong on the heap, not as locals.
#use cases
Moving oversized locals to heap or static storage
Returning heap pointers (never stack addresses) from factories
Reading segfaults as segment violations (text writes, stack smash)
Sizing stacks vs heaps deliberately in embedded link scripts

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.