Difference between the Stack Memory and Heap Memory is one o the most asked question in our subject viva or in project viva or an interview. And most of the time we got confused. So, from now onward no more confusions.
Let’s first Deal with
Before we go deep in explaining Stack Memory. We must understand What is Stack?
A Stack is an arrangement of Items in linear order. Like putting up of plate one on above.
We introduced a word LIFO which stands for “Last In First Out”
So, when we talk about Stack Memory The memory assigning to object takes place in linear order using Stack Arrangement.
For Example, We have a chain of function one function is calling another. So, memory assigning will take place when the code is compiling phase. It starts allocating memory from function 1 to function 4. But when function 1 calls function 2, function 1 will get suspended until function 2 returns something to function 1. So, in this case function 1, function 2, function 3 gets suspended until function 4 returns something. That the way we allocate memory to objects in the case of Stack Memory. So, when the function returns something to function 3, memory used by function 4 will be freed then It happens for function 3 and so on. So, it is very simple when to assign the memory and when to free the memory in Stack Memory Allocation.
Now the time is for second part i.e.[ad-banner][/ad-banner]
Heap Memory Allocation
Heap Memory Allocation to objects at run-time. And the size of Heap memory depends upon the size of virtual memory. Heap memory can be allocated at any time and can be free anytime. It depends on the run-time need of memory by the Objects. It is comparatively slower than Stack Memory in term of accessing the memory.
Note: Both memory allocation takes place in RAM only.
If you know the exact amount of memory is needed then you use stack memory for example memory allocation for primitive data types like int, float, char, double etc.
If you don’t know the amount of memory is needed then we use heap memory for example memory needed by the object at run-time for performing the calculation or etc.