C language

Q3: Memory allocation

Consider the C code

int main()
{
  int x=3;
  fun(x);
  return 0;
}
 

void fun(int n)
{
  n--;
  if (n!=0)
  {

    fun(n);
  }
}

Explain the allocation of memory in stack for the above program.

Ans: firstly a frame in stack is created and memory is allocated to store variable x with value 3.

www.exploreroots.com

And then function call is made to function fun() and a new frame is created in the stack. Firstly return address to main is saved in the stack. Next memory is allocated for variable n and 2 is stored in n.

www.exploreroots.com

Now n—is executed and n becomes 1. Then if statement is executed and another call to fun() is made and value 1 is passed. Again return address to function Fun() is saved and then value 1 is stored in variable n. execution of n- – decreases the value to 0.

www.exploreroots.com

Q-Why do sometimes we encounter an error named as ‘Stack Overflow ERROR’?

Ans: It occurs due to the infinite recursion calling. As we can see in the above case that in case of recursion (when a function calls itself), everyt ime a function is called new memory is allocated in the stack and hence in case of infinite incursion, a function is called infinite times and hence memory is allocated infinite times and hence we fall in shortage of memory in stack which is STACK OVERFLOW.

Now we have the next statement as if statement whose condition goes wrong as value of n is zero and hence no function call is made. After this we face a closed parantesis which means function is returned to the address saved in the address register.

www.exploreroots.com

Now we are in the function Fun() which was called first. Next statement in this function is also a closed parenthesis. Hence function again gets returned.

www.exploreroots.com

Now the main ends and program execution ends and hence whole stack is de-allocated and whole stack becomes empty

www.exploreroots.com

5 Replies to “Q3: Memory allocation

  1. Pingback: gunbarrelsusa.com

Leave a Reply

Your email address will not be published. Required fields are marked *