2

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

trincot
  • 317,000
  • 35
  • 244
  • 286
jonathan
  • 291
  • 1
  • 5
  • 17
  • `temp` is (maybe) on the stack and will be there untouched until, well, something touches it. Try putting another function call in between the call to `foo()` and the print statement and see what happens. – Keith Layne Oct 06 '11 at 18:32

3 Answers3

5

Because you are in Undefined Behavior land. Anything could happen.

Moral of the story: never return the address of a temporary!

John Dibling
  • 99,718
  • 31
  • 186
  • 324
  • But `temp` is. And `varFoo` is assigned the address of `temp`, which he returns, thereby returning the address of a temporary. – Dave Oct 07 '11 at 10:44
1

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

abettino
  • 146
  • 1
  • 3
  • The assertion that " The data will still be there in memory until something else writes over it. " is not a fact. Maybe it will be there, maybe it won't. You just don't know. Try running it in release mode & see what happens. – John Dibling Oct 06 '11 at 18:31
1

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

8762 is rubbish.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631