Skip to content

12. Stacks Vs Heaps

Madhav Anand edited this page Nov 11, 2020 · 2 revisions

Stack

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:

  1. We can't change the order of pushing function's stack frames. Thus, it is fixed.
  2. Stack Size is always limited/fixed in a system. May result, Stack Overflow. Example: Recursion
  3. Size can't be changed on runtime. We have to fix at compile time.

Heap

Heap is also called Free Storage and with this we can manually allocate and deallocate the memory at runtime.

  1. We can access memory globally.
  2. Heap size is not fixed. Can be expanded as big as virtual memory of our system.
  3. Size can be changed at runtime.

Quick Questions

  1. 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.

  2. 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.

  3. Give an example showing how can we change the size of variables during runtime ?
    Check this code

  4. What is new ?
    new is an operator.

  5. How can we access the memory allocated in heap ?
    With help of pointers only.

  6. Is delete() a function ?
    No, delete() is an operator.

  7. Why so much importance to memory deallocation ?
    Otherwise, it results in memory leak. Commonly seen as serious issue in server programs.

Clone this wiki locally