The code is still wrong. It may appear to work now, but won't next week. It may appear to work now, but change one small thing and it no longer "works".
Try this. Add another function, test2
:
int *test()
{
int a = 11;
return &a;
}
int test2()
{
int b = 13;
}
int main()
{
int *a;
a = test();
cout << "after test: " << *a << endl;
test2();
cout << "after test2: " << *a << endl;
return 0;
}
Now is 11
printed both times? Note that it could still print 11
twice, but it probably won't. We are, after all, still flirting with undefined behavior here.
But on my machine, I see:
after test: 11
after test2: 13
test2
has clobbered the space on the stack that my dangling pointer was pointing to. The code is incorrect. The variable defined inside the function test
is out of scope when the function exits, and is no longer valid. Maintaining a reference to it doesn't change this.