Stack vs Heap - Memory Layout in C
Learn the difference between stack and heap memory in C. Stack stores local variables and function frames; heap stores dynamically allocated data.
Stack vs Heap
The stack and heap are two distinct memory regions used by C programs.
Stack
- Grows downward in memory
- Stores local variables, function parameters, and return addresses
- Automatically managed: variables are created when a function is called and destroyed when it returns
- Fast allocation and deallocation
- Limited size; stack overflow can occur with deep recursion
Heap
- Grows upward
- Stores dynamically allocated memory via
malloc,calloc, orrealloc - Manually managed: you must call
free()to release memory - Slower than stack but flexible
- Used for data that must outlive the current function
When to Use Each
- Stack: Local variables, small fixed-size data
- Heap: Arrays whose size is unknown at compile time, data shared across functions, large structures