void foo(int** ptr) {
int value = 4;
*ptr = &value;
// **ptr = value;
}
int main(void) {
int value = 7;
int* ptr = &value;
foo(&ptr);
cout << *ptr << endl; // 4
return 0;
}
My Question is - as the value = 4
is no longer valid/out of scope after returning from foo
, why *ptr
is showing 4
instead of some garbage value?
Because you're returning a pointer to a local variable, this is undefined behavior. This includes "appearing" to work, but it's a terrible idea to rely on it in the general case.
In this specific case, the value is left on the stack, and it appears the generated code fetches *ptr
just after the call to foo
, and before any other function calls. As such, the value has not been overwritten by any other function calls.
If you were to instead insert a function call between the foo(&ptr)
and cout << ...
statements, the value would more than likely be garbage.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments