As the commenters mentioned, using the address of a local variable that has gone out of scope produces undefined behavior, i.e. anything may happen including the program working by pure chance. So, the short answer is don't do that.
If you are curious, though, this is how (at least in my environment), the program still manages to output 10
. The assembly shows that when the pointer is dereferenced, it is still pointing into what was the stack frame of the scopeProblem
function, which is unmodified since the call, so it still happens to contain 10
.
With that in mind, you can probably figure out why the following code prints out 2
(at least on my platform and compiler). The intervening call to foo
causes a new stack frame to be allocated which overwrites the stack frame from the call to scopeProblem
.
#include <cassert>
#include <iostream>
int* scopeProblem()
{
int *bret;
int b=10;
bret =&b;
return bret;
}
auto foo() {
int a = 0, b = 1, c = 2;
return a + b + c;
}
int main(int argc, const char *argv[]) {
auto ptr = scopeProblem();
auto a = foo();
std::cout << *ptr << std::endl;
assert(a == 3);
return 0;
}