The differences between stack and heap

stack and heap diagram

What is a stack 

A stack is a data structure used commonly in several programming languages. The reason why it is named a stack is because it’s structure as a collection of elements stacked on top of each other. An analogy to visualize what a stack is to picture several books stacked on top in a pile. In real life, the only way we can remove a book in a pile without affecting the others stacked in the pile is to remove the top book. Just like the analogy, the stack only allows the data operations at one end only, which is the top element of the stack.

stack diagram

What is a heap

The heap is used to dynamically allocate memory to variables at the run rime. This means that the memory needs to be manually released after use during run time. The size of the heap depends on amount of physical and virtual memory available and can grow/shrink at runtime. The heap memory is accessed via pointers (dynamic memory). Heap memory has the disadvantage of being slower than the stack.

Summary of the differences between stack and heap


Share this post