This code:
#include <iostream>
using namespace std;
int* fun()
{
int a = 5;
int* pointerA = &a;
cout << pointerA << endl;
return pointerA;
}
int main()
{
int* p = fun();
cout << p << endl;
return 0;
}
Prints the following:
0x[some address]
0
I understand that the variable a
is deallocated when the function fun()
returns, but why does cout << p << endl;
return 0? Shouldn't it still point to the same address in memory, even though variable is technically not there anymore? Is this a compiler feature or undefined behavior?
repro case
EDIT: I found the culprit. I am using CodeBlocks, and in this project's build options, there is a flag "optimize even more (for speed) [-O2]". If it is checked, I get 0
, and if I uncheck the flag, I get the same address 0x[some address]
, which is expected behavior.
I apologize for not mentioning my IDE.
Accessing the return value of fun
has implementation-defined behavior, as it returns an invalid pointer value (see the quote below, why). In particular platforms, it may even generate a runtime fault. So, p
's value is implementation-defined as well. Most likely, it will became invalid pointer value, so accessing it is implementation-defined.
basic.std/4:
When the end of the duration of a region of storage is reached, the values of all pointers representing the address of any part of that region of storage become invalid pointer values. Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With