Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer can point local variable's memory outside it's scope? [duplicate]

Tags:

c++

c

pointers

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?

like image 302
Kaidul Avatar asked Jun 05 '26 11:06

Kaidul


2 Answers

Formal answer: undefined behavior.

Practical answer: no other operation on the stack has yet to override that value.

like image 198
barak manos Avatar answered Jun 07 '26 02:06

barak manos


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.

like image 31
Drew McGowen Avatar answered Jun 07 '26 01:06

Drew McGowen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!