Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
Consider the following simple C++ code:
#include <iostream>
struct Test
{
Test( int i )
: ref( i ),
ptr( &i ) {}
int &ref;
int *ptr;
};
int main()
{
Test t( 5 );
std::cout << t.ref << std::endl;
std::cout << *t.ptr << std::endl;
return 0;
}
The class Test stores a pointer and a refernce to the local variable i living on the stack. I would presume that i get's destroyed after returning from the Test constructor. But obviously this is not the case. As this is the output of the program:
5
134513968
The result of the access to the pointer is what I would expect: a random value that changes with every run. But the reference access always results in 5 - just if the local variable i still exists.
Can anyone explain this behaviour to me? I'm using g++ on 64bit Linux (version 4.6.3).
Regards, enuhtac