I know the lifetime of the local variable in the function will finish after the function completed. But I found the example shown below, it can work.
int & foo()
{
int b = 5;
int &a = b;
return a;
}
int main()
{
int &c = foo();
cout<<c;
return 0;
}
Also, I tried to use pointer to point the local variable and return the pointer. It can work too.
int * foo(){
int b = 5;
int *a = &b;
return a;
}
int main()
{
int *c = foo();
cout<<*c;
return 0;
}
I am so confused. I've learnt that the lifetime of the local variable will end after the function completed because the local variable is stored in the stack memory. It means that the memory of the local variable will be released after the function completed. Then, the pointer or reference will point to nothing.
However, the two example above verified that my concept is wrong. What is the reason?