Skip to content

Stack and heap

This page deliberately lives several folders deep. The filesystem is the note tree; no second navigation database is involved.

The note tree
notes/
└── systems/
└── memory/
└── stack-and-heap.md

Tags cut across that tree. The hierarchy answers where does this note belong? while tags such as #c and #memory answer what else is it related to?

RegionUsually containsLifetime
StackCall frames, parameters, automatic variablesUntil the function returns
HeapDynamically allocated objectsUntil explicitly released or reclaimed

The names describe allocation strategies, not C types. A pointer variable can live on the stack while referring to an object on the heap.

#include <stdlib.h>
int *make_value(void) {
int *value = malloc(sizeof *value);
if (value != NULL) *value = 42;
return value;
}

The pointer variable value is automatic; the allocation returned by malloc remains alive after the function returns and must later be passed to free.

Image inspectorDrag to pan · wheel to zoom
100%