函数返回后,局部变量仍然存在 [英] Local variable still exists after function returns

查看:402
本文介绍了函数返回后,局部变量仍然存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为,一旦函数返回,所有在其中声明的局部变量(使用static关键字禁止的局部变量)都将被垃圾回收.但是,当我尝试以下代码时,在函数返回后,它仍会打印该值.有人可以解释为什么吗?

I thought that once a function returns, all the local variables declared within (barring those with static keyword) are garbage collected. But when I am trying out the following code, it still prints the value after the function has returned. Can anybody explain why?

int *fun();
main() {
  int *p;
  p = fun();
  printf("%d",*p); //shouldn't print 5, for the variable no longer exists at this address
}
int *fun() {
  int q;
  q = 5;
  return(&q);
}

推荐答案

如果您确实希望它松散该值,则可能会在其中至少使用几行代码来调用另一个函数它,然后通过访问该位置进行打印. 很有可能届时您的价值将被覆盖.

If you really want it to loose the value, perhaps call another function with at least a few lines of code in it, before doing the printf by accessing the location. Most probably your value would be over written by then.

但是正如已经提到的,这是未定义的行为.您永远无法预测它何时崩溃(或完全崩溃).但是您不能依靠它的改变或保持不变",并以任何这些假设为应用程序编写代码.

But again as mentioned already this is undefined behavior. You can never predict when (or if at all) it crashes or changes. But you cannot rely upon it 'changing or remaining the same' and code an application with any of these assumptions.

我想说明的是,当您从上一个返回后再进行另一个函数调用时,另一条激活记录被推入堆栈,最有可能是在覆盖上一个包含您正在通过指针访问其值的变量的上一个记录

What i am trying to illustrate is, when you make another function call after returning from previous one, another activation record is pushed on to the stack, most likely over writing the previous one including the variable whose value you were accessing via pointer.

实际上,没有一个主体实际上是在进行垃圾回收,或者一旦某个函数及其数据超出范围,就会执行例如memset 0的操作.

No body is actually garbage collecting or doing a say memset 0 once a function and it's data goes out of scope.

这篇关于函数返回后,局部变量仍然存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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