Topics / Pointers & Memory / Q8
What is the difference between stack and heap?
Short answer: The stack holds function-local data automatically: space is reserved on function entry by moving the stack pointer and released on return, so it is fast and deterministic but small and limited to the function's lifetime. The heap holds memory you request explicitly with malloc and release with free; it lives until freed and can be large, but allocation is slower, can fail, and can fragment.
| Stack | Heap | |
|---|---|---|
| Allocation | automatic (function entry) | explicit (malloc/free, new/delete) |
| Speed | one instruction (adjust SP) | allocator search; varies |
| Lifetime | until the function returns | until free |
| Size | small, fixed per thread/task (KB on MCUs, 8 MB default on Linux) | as much RAM as is available |
| Fragmentation | none | yes, over time |
| Failure mode | overflow: silent corruption or a fault | malloc returns NULL |
| Thread safety | each thread has its own | shared; allocator needs locking |
| Determinism | yes | generally no |
What is on the stack: local variables, function arguments that do not fit in registers, return addresses (LR saved by the callee), saved registers, and on Cortex-M the exception frame pushed automatically on interrupt entry (8 words, more with the FPU).
Common bugs
- Returning a pointer to a local (the stack frame is gone after return).
- Large local arrays (
char buf[4096];in a task with a 2 KB stack). - Heap: leaks, double free, use after free, writing past the allocated size (corrupts the allocator's metadata, crashing much later in an unrelated
malloc).
Embedded guidance
- Prefer static allocation and stack allocation with known bounds; measure the worst-case stack per task (high-water marks, static analysis).
- If you need dynamic memory, allocate at start-up only, or use fixed-size memory pools.
- With FreeRTOS, choose the heap scheme deliberately:
heap_1(no free),heap_4(coalescing first-fit),heap_5(multiple regions), or fully static allocation (configSUPPORT_STATIC_ALLOCATION).