3

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?

Pooty Lim
  • 51
  • 1
  • 3
  • 2
    The variable `n` is a ***local*** variable, whose life-time ends when the function returns. Returning a pointer to it would make no sense as the pointer would become immediately invalid. – Some programmer dude May 23 '21 at 09:21
  • You are returning the address of a function parameter which is a temporary. That's Undefined Behavior. (I.e. whatever you got is unreliable.) – Scheff's Cat May 23 '21 at 09:22
  • 2
    The second variant have another problem (with how you currently use the function): A memory leak. You allocate memory with `new` but you never `delete` it. – Some programmer dude May 23 '21 at 09:29

1 Answers1

1

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.)

songyuanyao
  • 169,198
  • 16
  • 310
  • 405