0
#include<stdio.h>
int *sample();
int main(void)
{
  int *p;
  p=sample();
  printf("%d",*p);
  return 0;
}

int *sample()
{
  int *p,x=10;
  p=&x;
  return p;
}

In the code above x is local variable. When I compiled above with gcc I'm getting output:

10

A local variable is only alive in the function where it is declared and as the control comes out of function local variable should be de-allocated. But this is not happening. wWy its printing 10? Can anyone explain this behaviour?

DrYap
  • 6,525
  • 2
  • 31
  • 54
vinay hunachyal
  • 3,781
  • 2
  • 20
  • 31
  • 5
    You're [stealing the hotel key](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794) – Ingo Leonhardt Aug 15 '13 at 10:19
  • For anyone who doesn't get the reference @Ingo made, see http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope which is also a great answer – jcoder Aug 15 '13 at 10:29
  • Ah yes, that one. Still a fun analogy to read. – Dennis Meng Dec 30 '13 at 03:36

4 Answers4

4

While the behavior is officially undefined in the C standard, in practice values in memory stick around until something else overwrites them.

More details can be found at Why do I have values in my array that I didn't assign?

Community
  • 1
  • 1
Gilbert
  • 3,740
  • 17
  • 19
2

I modified your program just a little. See below.

#include<stdio.h>
int *sample();

void donothing ();

int main(void)
{
  int *p;
  p=sample();

  donothing();

  printf("in main(), *p = %d\n",*p);
  return 0;
}

int *sample()
{
  int *p,x=10;
  p=&x;

  return p;
}

void donothing ()
{
  int x[10], y;

  y = 17;
  return;
}

When I run it now, here's what I get ...

amrith@amrith-vbox:~/so$ ./stack 
in main(), *p = 17
amrith@amrith-vbox:~/so$ 

It is never safe to return the address of a local variable as that is typically established on the stack and can be overwritten.

amrith
  • 953
  • 6
  • 17
0

The program has undefined behavior. Returning reference of a local variable has unpredictable behavior and you were just unlucky that the value was still around.

Mahesh
  • 34,573
  • 20
  • 89
  • 115
0

There's no garbage collection in C.

x,a local variable, cease to exist, when sample exits

Your case is an Undefined Behavior.

P0W
  • 46,614
  • 9
  • 72
  • 119