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