A stack can be per-thread, whereas the heap is global. Function calls and their arguments go to the stack, and variables and similar go to the heap. The stack is normally managed automatically (you can only call functions), whereas the heap can be manipulated manually (garbage collectors help)
The stack is continuous whereas the heap can be fragmented
Comparison Chart
Parameter | Stack | Heap |
---|---|---|
Basic | Memory is allocated in a contiguous block. | Memory is allocated in any random order. |
Allocation and De-allocation | Automatic by compiler instructions. | Manual by the programmer. |
Cost | Less | More |
Implementation | Easy | Hard |
Access time | Faster | Slower |
Main Issue | Shortage of memory | Memory fragmentation |
Locality of reference | Excellent | Adequate |
Safety | Thread safe, data stored can only be accessed by the owner | Not Thread safe, data stored visible to all threads |
Flexibility | Fixed-size | Resizing is possible |
Data type structure | Linear | Hierarchical |
Preferred | Static memory allocation is preferred in an array. | Heap memory allocation is preferred in the linked list. |
Size | Smaller than heap memory. | Larger than stack memory. |
Source: https://www.geeksforgeeks.org/stack-vs-heap-memory-allocation/