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?
Formal answer: undefined behavior.
Practical answer: no other operation on the stack has yet to override that 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With