In this post, we will understand the difference between Stack and Heap
Stack
It is a linear data structure.
Memory is allocated in a contiguous (continuous) block.
The memory for a stack is allocated and deallocated automatically using the instructions of the compiler.
It costs less to build and maintain a stack.
It is easy to implement.
It is fixed in size; hence it is not flexible.
Its only disadvantage is the shortage of memory, since it is fixed in size.
If all the blocks are not occupied, memory gets wasted too.
It takes less time to access the elements of a stack.
It has an excellent locality of reference.
Heap
It is a hierarchical data structure.
Memory is allocated in a random fashion.
The memory is allocated and deallocated manually by the programmer.
It is costly to build and maintain a heap.
It is difficult to implement a heap structure.
It takes more time to access elements of a heap.
The disadvantage of heap is fragmentation of memory.
Resizing is possible in heap.
Hence, memory is not wasted.
It has adequate locality of reference.
A process inside main memory −