0
votes

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.

1
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
the dupe @Peter refered to contains one of the best answers I had ever seen on SO, with almost 2000 upvotes.. - amit
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
@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

1 Answers

3
votes

"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.