What is stack and heap? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

What is stack and heap?

Please explain with the help of real life analogy.

17th Jul 2017, 8:42 PM
Umer Khan
Umer Khan - avatar
2 Answers
+ 11
They are both special regions of your computer's memory. One is managed and optimized by the CPU (the Stack aka "Static memory") and the other one is NOT managed automatically by the CPU for you (the Heap aka "Dynamic memory") ■ STACK It contains things whose size is known at compilation: temporary variables created by each function. It is named a "stack" because it's structured as a collection of elements stacked on top of each other. An analogy could be a pile of books 📚. The only way we can remove a book in a pile without affecting the others stacked is by removing the top book. The same thing applies for the stack, it allows the data operations at one end only, which is the top element of the stack. ■ HEAP It's a more free-floating region of memory (and larger), it is for variables allocated at runtime and their size isn't well known at compilation. This means that the memory needs to be manually released after use during runtime. The size of the heap depends on amount of physical and virtual memory available and can grow or shrink at runtime, that's why the analogy I use is a balloon🎈 :) also, the heap memory is accessed via pointers and it has the disadvantage of being slower than the stack.
17th Jul 2017, 11:01 PM
Pao
Pao - avatar
+ 3
the stack and the heap are two memory locations. Value Types (primitive data like bool or integers) are stored directly in the stack. On the other hand Reference Types (objects) only have their memory address stored in the stack, their actual location is in the heap. This picture may help you out https://4.bp.blogspot.com/-c5HqECaGDNw/U_OCdWlEQHI/AAAAAAAAAGU/nqi6CGRI-Rc/s640/stack%2Band%2Bheap.png
17th Jul 2017, 9:34 PM
Edi Lipovac
Edi Lipovac - avatar