Stack and Heap, both are stored in a computer’s RAM. The figure below shows the basic concept of stack and heap memory.

stack and heap diagram

What is a stack?

A stack is a data structure used commonly in several programming languages. Similarly, the reason why it is named a stack is that its structure is a collection of elements stacked on top of each other. In other words, the stack is similar to a picture of several books stacked on top of a pile. In real life, the only way we can remove a book from 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 time. In other words, the memory needs to be manually released after use during run time. Similarly, the size of the heap depends on the amount of physical and virtual memory available and can grow/shrink at runtime. The heap memory is accessed via pointers (dynamic memory). Above all, heap memory has the disadvantage of being slower than the stack.

Summary of the differences between stack and heap

table

Share this post

FAQ's

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. A stack only allows the data operations at one end only, which is the top element of the stack.

What is 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).

What are the differences between stack and heap?

Stack operates in in FILO First in last out principle. Heap variables are not allocated sequentially. Stack is fixed in size. Heap can shrink and grow.