0

Possible Duplicate:
Can a local variable's memory be accessed outside its scope?

I was refreshing the knowledge about how memory internally works, and I faced the confusion. Here is sample code

int * func(){
   int retval = 3;
   return &retval;
}

int main(void){
   int *ptr = func();
   printf("address return from function %p and value %d\n", ptr, *ptr);
}

My understanding regards how stack memory works on a routine, is when a function was called, it is pushed on the stack. And lifetime of local variables within this routine would no longer valid once the function returns. So returning address of local variable seems like not valid, but when I test this code, it actually returns its address and still valid after the function returns.

am I misunderstanding the concept ? Appreciated any comments, Thanks.

Community
  • 1
  • 1
REALFREE
  • 4,378
  • 7
  • 40
  • 73
  • In short, what you are doing is not valid, but that's doesn't mean that it won't work in certain situations. – Peter Alexander Aug 18 '11 at 23:05
  • the dupe @Peter refered to contains one of the best answers I had ever seen on SO, with almost 2000 upvotes.. – amit Aug 18 '11 at 23:06
  • 1
    Invalid and doesn't work are two different things. Until the data is overwritten (by another function call), you can still access it even though you shouldn't. If you called another function between `func` and `printf`, you would get some other number instead of 3. – ughoavgfhw Aug 18 '11 at 23:07
  • @ughoavgfhw: Or if a signal handler happened to run, or if the compiler decided to put some stuff temporarily on the stack, or ... – R.. GitHub STOP HELPING ICE Aug 19 '11 at 01:17

1 Answers1

3

"Testing the code" is not a meaningful way to determine if something is valid or not. Your code produces undefined behavior. One possible manifestation of undefined behavior is that the code might appear to be "working". In other words, you simply got lucky.

To answer the question: no, it is not valid to return a pointer to a local variable and it is not valid to dereference such a pointer. Any attempts to do so lead to undefined behavior.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • It's not invalid just to return it, at least not if you cast it to an integer type. This might be useful as a (weak, but still potentially useful) source of entropy - essentially, harvesting entropy from the system's ASLR. – R.. GitHub STOP HELPING ICE Aug 19 '11 at 01:18
  • Note that some people **wrongly** dereference the pointer after it's no longer valid as a source of entropy too. This is not legal C and an implementation is perfectly justified in making such usage crash. But my example is legal. – R.. GitHub STOP HELPING ICE Aug 19 '11 at 01:19