Stack Allocation vs Heap Allocation

Posted September 9, 2022 by Rohith and Anusha ‐ 1 min read

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

BasicMemory is allocated in a contiguous block.Memory is allocated in any random order.
Allocation and De-allocationAutomatic by compiler instructions.Manual by the programmer.
Access timeFasterSlower
Main IssueShortage of memoryMemory fragmentation
Locality of referenceExcellentAdequate
SafetyThread safe, data stored can only be accessed by ownerNot Thread safe, data stored visible to all threads
FlexibilityFixed-sizeResizing is possible
Data type structureLinearHierarchical
PreferredStatic memory allocation is preferred in array.Heap memory allocation is preferred in the linked list.
SizeSmall than heap memory.Larger than stack memory.
quick-references blog stack heap differences

Subscribe For More Content