0

Confused of Dynamic Memory allocation. What is the best way to understand it?real life analogy helpful.

3rd Jul 2017, 5:45 AM
Sai Yerni Akhil
Sai Yerni Akhil - avatar
2 odpowiedzi
0
Imagine you have a drawer destined for socks. It has only enough space to store 15 pairs of socks. One day you invite a bunch of friends, and as usual, they bring a lot of socks with them (because that happens everytime haha). You don't know with certainty how many socks you will have in the end, and that worries you A LOT. But! You remember your roomate is not gonna spend the night there, and he has a completely empty closet. PERFECT! Just reserve some space for the socks and store them there temporarily! If you need more space, then relocate them in a bigger part of the closet. Once everyone leaves, there's no need for you taking space from your roomate's closet anymore, so you remove all evidence of it being used (because we all know Henry is a little bit annoying when it comes to his personal space xD). Even though you had no space left in your drawer, you were able to succesfully store a previously unknown number of socks by using the space available next to you. Now, let's call everything by its proper name: socks drawer: Stack. Henry's closet: Heap. The size of the stack must be known at compile time, it cannot be changed dinamically, just as the drawer cannot store more than 15 socks. The heap is an enormous place where you can grab memory as you wish, EVEN AT RUNTIME! If you need to accomplish a task which requires you to expand your memory capacity, this is where you should be doing all of this! The heap is commonly used for storing things like arrays and user input, since you don't know exactly how much space is it gonna take. I hope this wasn't too long!
3rd Jul 2017, 6:48 AM
Alejandro Aristizabal
Alejandro Aristizabal - avatar
0
Thank you very much..! I've got this understood.!
3rd Jul 2017, 8:41 AM
Sai Yerni Akhil
Sai Yerni Akhil - avatar