From what I know, if a function returns a pointer to a local variable, dereferencing the returned pointer later causes undefined behavior. However, this article says that things can be made to work if the function also defines a pointer to the local variable and return that pointer. While the pointer returned by
int* foo()
{
int x = 20;
return &x;
}
cannot later be used retrieve the value 20, the article claims that
int* fun()
{
int x = 20;
int* ptr = &x;
return ptr;
}
works. I compiled and ran fun()
together with
int main()
{
int *p = fun();
cout << *p;
return 0;
}
The compiler did not complain and the program indeed printed out 20. (I was surprised.)
Why is that fun
works while foo
does not?