C language

Q4: Memory Allocation

What is the output of the following code?

int main()
{
  int*x;
  x = abc();
  printf(“%d”,*x);
  return 0;
}

int* abc()
{
  int y=3;
  return (&y);
}
  • (a) 3              (b) 5       (c) Can’t say

Ans: Many would answer it as 3 but it is wrong. The way we have tried to do it is wrong. As we enter into main we have a memory allocated for variable x and then function abc is called.

www.exploreroots.com

Now as function abc() is called, a new frame is added in the stack. We save the return address to main in the stack. Then a variable y is declared.

www.exploreroots.com

Leave a Reply

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