local memory address is valid after function return?

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 %dn", 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.


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

链接地址: http://www.djcxy.com/p/36334.html

上一篇: 指向C ++中的局部变量

下一篇: 本地内存地址在函数返回后是否有效?