-1
#include<stdio.h>
#include<conio.h>

int *x()
{
  int y=10;
  return (&y);
}

void main()
{
  int *p;
  clrscr();
  p=x();
  printf("%d",*p);  // Output 10
  getch();
}

Here when we call x() function, activation record of x is pushed onto the stack. When we come out of that function, the activation record and all the local variables inside it are destroyed. So, how are we able to access the value of y in main function after coming out of x function ? The output value should be some garbage value as "y" variable is destroyed.

Zephyr
  • 1,521
  • 3
  • 22
  • 42
  • 2
    Where does it say it has to be a garbage value? Which part of the C specification makes such a guarantee? – kaylum Jul 09 '17 at 10:19
  • I mean garbage value or any undefined value. My point is value of y which is 10 should not be the output right? – Zephyr Jul 09 '17 at 10:20
  • 3
    No that's an entirely incorrect assumption. Undefined means any value - including 10. – kaylum Jul 09 '17 at 10:21

3 Answers3

2

Function x returning a pointer to an automatic local variable and causing undefined behavior. In this case any expected or unexpected result can be seen.

haccks
  • 104,019
  • 25
  • 176
  • 264
1

Local variables have a limited lifetime which only extends inside the block {} they are defined. They have a local-scope.

When the control reaches the end of the block all the storage for the variables in it is not guaranteed to not be writable.

That portion of memory can be re-used. Will it be? who knows.

This translates to: undefined behaviour!

Community
  • 1
  • 1
Davide Spataro
  • 7,319
  • 1
  • 24
  • 36
0

Is not like "y" gets destroyed. Its memory region is labelled as "writable"

So you may either find your "y", as well as a garbage value. After all, the function is returning a pointer, not the variable itself