Dynamic Memory Management

stack versus heap allocation

Every value your program stores in memory lives somewhere, and for most variables you have a choice of two places: the stack or the heap. They are both regions of the process's memory, but they behave so differently that choosing between them is one of the most basic decisions in C. The short version: the stack is fast and automatic but tied to the function call; the heap is flexible but manual.

Stack allocation is what happens automatically when you declare an ordinary local variable, like int x or char buf[64]. The space is reserved when the function is entered and released the instant it returns, simply by moving the stack pointer — there is no malloc, no free, no bookkeeping per object, and it is extremely fast. The cost is two limits: the lifetime is bounded by the function call (the variable vanishes at return, so you cannot hand it back to your caller), and the size must be a fixed amount known when the function runs, drawn from a stack that is relatively small (often a few megabytes), so a huge or unknown-sized array does not belong there. Heap allocation, via malloc and friends, removes both limits: the block lives until you free it (so it can outlive the function and be returned to a caller), and its size can be any value computed at run time, drawn from a much larger pool. The price is that you manage it by hand — every malloc needs a matching free, and the bugs in this field (leaks, dangling pointers, double-frees) are all heap bugs.

The practical rule: prefer the stack when a value's life fits inside one function and its size is modest and known — it is faster and cannot leak. Reach for the heap when the object must outlive the function that created it, must be shared, must grow, or is too large or its size is unknown until run time. A useful instinct: if you find yourself wanting to return a pointer to a local variable, that is the signal you need the heap instead.

void f(void) { char small[64]; /* STACK: auto, freed at return, fixed size */ char *big = malloc(n); /* HEAP: lives until free(big), size known at run time */ /* ... */ free(big); } /* small disappears automatically here */

Stack: automatic and fast but scope-bound and fixed-size. Heap: flexible and long-lived but manually freed.

The stack here is a memory region that grows with function calls — not the LIFO stack data structure. Allocating a very large array on it can overflow the stack and crash the program.

Also called
automatic vs dynamic storagewhere to put a variable自動配置與動態配置