Regading C++ pointers and functions

Viewed 38

I have a code in C++.

int* func(int n) {
    int* v= &n;
    return v;
}
int main()
{
    int* c = func(5);
    int* k = func(9);
    cout<<*c;
}

This code returns a 9 instead of a 5. However, when I change the func to

int* func(int n) {
    int* v= new int(n);
    return v;
}

This returns a 5 as expected. Is there a reason why the 1st one doesn't work but the 2nd one does?

1 Answers

func is returning a pointer to parameter n. Note that n is declared as pass-by-value, it'll be destroyed when the function ends. Then the returned pointer is always dangling, dereference on it leads to UB.

The 2nd code snippet doesn't have such issue. func is returning a pointer newed in function body, it's valid even after function ends. (BTW the returned pointer has to be deleteed somewhere to avoid memory leak.)

Related