Is there any thing wrong in the following code?
#include <iostream>
using namespace std;
int* pointer;
void assign() {
int a = 2;
pointer = &a;
}
int main() {
assign();
cout<<*pointer<<endl;
}
According to my knowledge, 'a' exists in stack memory when executing assign(). Hence, after function assign() runs, the memory allocated to 'a' should be released. But in assign(), the address of 'a' is allocated to 'pointer' which exists in data segment. 'pointer' exits in the whole life of this program.
But after assign(), we print out *pointer whose corresponding variable has been released before. Is there any thing wrong will happen? Or is it a undefined behavior?
In fact, the above program can run correctly to print out the right value.