I'd like to know why is it that the data that is pointed to when you return from a function, is not deleted immediately. In the snippet of code below,I expect that when I return the address of x to the pointer to initialise it when returning from function, the data stored in the address of x should be deleted immediately. However I am still able to get the correct value in main and then only after one more line of code does it suddenly turn into garbage? Why does this not happen immediately
int* function(int x)
{
cout << x << endl; // This outputs 5 as expected
return &x;
}
int main()
{
int* a = function(5);
cout << *a; // This still outputs 5. Why?
cout << endl;
cout << *a; // It is garbage here as expected
cout << endl;
return 0;
}
Thanks