Stack Allocation happens on contiguous blocks of memory. We call it a stack memory allocation because the allocation happens in the function call stack. The size of memory to be allocated is known to the compiler and whenever a function is called, its variables get memory allocated on the stack. Heap Allocation is allocated during the execution of instructions written by programmers. Note that the name heap has nothing to do with the heap data structure. It is called heap because it is a pile of memory space available to programmers to allocate and de-allocate.
Stack allocation and Heap allocation comparison is as follows
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 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 array. | Heap memory allocation is preferred in the linked list. |
Size | Small than heap memory. | Larger than stack memory. |