0

From what I know, if a function returns a pointer to a local variable, dereferencing the returned pointer later causes undefined behavior. However, this article says that things can be made to work if the function also defines a pointer to the local variable and return that pointer. While the pointer returned by

int* foo()
{
    int x = 20;
    return &x;
}

cannot later be used retrieve the value 20, the article claims that

int* fun()
{
    int x = 20;
    int* ptr = &x;
    return ptr;
}

works. I compiled and ran fun() together with

int main()
{ 
    int *p = fun();
    cout << *p;
    return 0;
}

The compiler did not complain and the program indeed printed out 20. (I was surprised.)

Why is that fun works while foo does not?

lamc
  • 347
  • 2
  • 5
  • 5
    UB means anything can happen. It can appear to work for the first 99 days you test and fail on the 100th. It's still broken. – drescherjm Jul 25 '22 at 20:21
  • 5
    It's still Undefined Behavior. The local variable still doesn't exist. The article is garbage. – sweenish Jul 25 '22 at 20:21
  • 4
    Don't believe everything/anything you read on geeks for geeks – Alan Birtles Jul 25 '22 at 20:21
  • Just look at the locallity of the variable. Do you think it's a good idea to access the variable's grave? – Ted Lyngmo Jul 25 '22 at 20:22
  • 11
    *"the pointers get stored in the heap and remain even after the fun call get over."* - is not even remotely true and demonstrates that the author does not understand pointers in the slightest – UnholySheep Jul 25 '22 at 20:22
  • 5
    "The compiler did not complain" That's the only believable effect of this change. The problem is still there, but the change makes it just a little harder for the compiler to see. – Ben Voigt Jul 25 '22 at 20:24
  • Never actually looked at geeks for geeks website before, but seen comments about it being unreliable. You've just shown me that it is totally disconnected from reality or how anything really works. Thank you. – Avi Berger Jul 25 '22 at 20:26
  • 3
    The example code in that article starts with `#include `, which also indicates poor quality. See [Why should I not `#include `?](https://stackoverflow.com/q/31816095/1458097) – heap underrun Jul 25 '22 at 20:30

0 Answers0