Stack and Heap, both are stored in a computer’s RAM. The figure below shows the basic concept of stack and heap memory.
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.
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