我不明白为什么这个程序会打印 8762 作为结果
可能的重复:
局部变量的内存可以在其作用域之外访问吗?< /a>
#include <iostream>
double *foo(){
double *varFoo = new double;
double temp = 8762;
varFoo = &temp;
return varFoo;
}
int main(void){
double *newVar = foo();
std::cout<<*newVar<<std::endl;
std::cin.get();
return 0;
}
我知道指针 varFoo 将在堆中创建,因此将一直保留在那里,直到我调用 delete,但是函数 foo 内部的临时变量又如何呢?
它是一个局部变量,一旦 foo 函数的调用结束,存储临时变量值的地址就会被释放,对吗?
那么为什么我得到的结果是 8762 而不是垃圾呢?
谢谢
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
#include <iostream>
double *foo(){
double *varFoo = new double;
double temp = 8762;
varFoo = &temp;
return varFoo;
}
int main(void){
double *newVar = foo();
std::cout<<*newVar<<std::endl;
std::cin.get();
return 0;
}
I understand that the pointer varFoo will be created in the heap and thus will stay there until I call delete, but what about temp variable which is inside the function foo?
it's a local variable and as soon as the call of the foo function ends, the address where the temp variable's values will be stored will just be freed right?
so why do I get 8762 as a result instead of rubbish?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为你处于未定义行为领域。什么事情都可能发生。
这个故事的寓意是:永远不要返回临时地址!
Because you are in Undefined Behavior land. Anything could happen.
Moral of the story: never return the address of a temporary!
不,它不一定会立即被释放。数据仍将保留在内存中,直到有其他内容覆盖它为止。由于您的程序在调用该函数后不会执行太多操作,因此该值没有机会被覆盖,因此它仍然是“正确的”。
No it won't necessarily be freed right away. The data will still be there in memory until something else writes over it. Since your program does not do much after calling the function, there is not an opportunity for the value to be overwritten so it is still "correct".
8762是垃圾。
8762 is rubbish.