Stack vs Heap Memory
Stack memory and heap memory are both parts of a running program's memory, but they hold different data. The stack is small and fast. It holds the local values of the functions running now, and they vanish when the function returns. The heap is large and slower. It holds data that must live longer or grow, until it is freed.
Stack Memory
A small, fast part of memory. It holds the values of running functions.
Stack memory is a small, fast area that holds the values of the functions running now. Each call to a function puts a new block on top of the stack. The block holds that function's local variables. When the function returns, its block comes off the top at once. On Linux the stack for a program's main thread is usually 8 MB. So a function that calls too deep causes a stack overflow.
Heap Memory
A big part of memory. Its data can last longer than one function.
Heap memory is a large area for data that must outlive one function call. It also holds data whose size is not known ahead of time, like a list that keeps growing. The program asks for a piece of the heap when it needs one. That piece stays until it is freed, by you in C or by the garbage collector in most other languages. The heap is bigger than the stack but slower to use.
In one line
- Stack Memory
- A small, fast part of memory. It holds the values of running functions.
- Heap Memory
- A big part of memory. Its data can last longer than one function.