函数返回后本地内存地址是否有效? [英] local memory address is valid after function return?

查看:91
本文介绍了函数返回后本地内存地址是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
能否在其范围之外访问局部变量的内存? /a>

我正在刷新有关内存内部工作原理的知识,我面临着困惑.这是示例代码

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);
}

我对栈存储器如何在例程上工作的理解是,当一个函数被调用时,它被压入栈中.一旦函数返回,此例程中局部变量的生存期将不再有效.因此,返回局部变量的地址似乎无效,但是当我测试此代码时,它实际上返回了其地址,并且在函数返回后仍然有效.

我误解了这个概念吗?感谢任何评论,谢谢.

解决方案

测试代码"不是确定某项内容是否有效的有意义的方法.您的代码产生未定义的行为.未定义行为的一种可能表现是该代码似乎在正常工作".换句话说,您只是很幸运.

要回答这个问题:不,返回指向局部变量的指针是无效的,并且取消引用此类指针也是无效的.任何尝试都会导致未定义的行为.

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.

解决方案

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

这篇关于函数返回后本地内存地址是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆