开发者

I can't understand why this program prints 8762 as a result [duplicate]

开发者 https://www.devze.com 2023-04-11 01:13 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Can a local variable's memory be accessed outside its scope?
This question already has answers here: Closed 11 years ago.

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;
    开发者_Python百科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


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


so why do I get 8762 as a result instead of rubbish?

8762 is rubbish.

0

精彩评论

暂无评论...
验证码 换一张
取 消