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
Returning the address of a local variable invokes undefined behavior. So, you're just lucky.
The local variable (allocated on the stack) gets deleted when it leaves it's scope, which in your case is when
function()
ends. However, after the variable leaves the scope, the memory it occupies is not rewritten immediately and unless that memory is reused the value ofx
will stay there.Since it invokes UB, your attempt to read the contents of that memory can result in reading the right value, reading garbage, your programm crashing, or anything else.