-
Notifications
You must be signed in to change notification settings - Fork 9
12. Stacks Vs Heaps
Whenever a function is called, the function's stack frame is added/pushed to the memory stack.
Local Variables scope are limited to the function itself.
Following things to Stack:
- We can't change the order of pushing function's stack frames. Thus, it is fixed.
- Stack Size is always limited/fixed in a system. May result, Stack Overflow. Example: Recursion
- Size can't be changed on runtime. We have to fix at compile time.
Heap is also called Free Storage and with this we can manually allocate and deallocate the memory at runtime.
- We can access memory globally.
- Heap size is not fixed. Can be expanded as big as virtual memory of our system.
- Size can be changed at runtime.
-
Why can't we achieve the same with pointers or Pass by Reference ?
We can access the local variables of the main function in any other function by Pass by reference. But we can't access the local variables of the other function in main function. Still didn't get it ! Give a try. -
Can't we use global variables for the same, why we need this dynamic memory allocation ?
It serves the purpose as global variables do, but this gives an advantage of changing the size of memory at runtime. -
Give an example showing how can we change the size of variables during runtime ?
Check this code -
What is
new
?
new
is an operator. -
How can we access the memory allocated in heap ?
With help of pointers only. -
Is
delete()
a function ?
No,delete()
is an operator. -
Why so much importance to memory deallocation ?
Otherwise, it results in memory leak. Commonly seen as serious issue in server programs.