local memory address is valid after function return? [duplicate]

人走茶凉 提交于 2019-12-25 01:56:09

问题


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:


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



来源:https://stackoverflow.com/questions/7115157/local-memory-address-is-valid-after-function-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!