Memory Management in Depth
Prerequisites: Networking basics: sockets
A running C program's memory splits into distinct regions: the
stack (local variables, growing and shrinking automatically
with function calls), the heap (malloced memory, managed
entirely by hand), and static storage (global and static
variables, allocated once for the program's whole lifetime).
int global = 1; // static storage
void example(void) {
int local = 2; // stack — gone when example() returns
static int persistent = 3; // static storage — keeps its value
int *heap = malloc(sizeof(int)); // heap — lives until free()d
*heap = 4;
free(heap);
}
A static local variable retains its value between calls, unlike an
ordinary local — useful for a counter that persists without needing
a global variable visible to the whole file.
Common mistakes
- Returning a pointer to a local (stack) variable from a function — that memory is invalid the instant the function returns, even though the pointer itself still looks valid.