0

We see 2 Examples which both have dangling references: Example A:

int& getref()
{
        int a;
        return a;
}

Example B:

int& getref()
{
        int a;
        int&b = a
        return b;
}

We call them both with this same main function:

int main()
{
        cout << getref() << '\n';
        return 0;
}

In Example A I get a compiler warning and the expected Segfault on reading the dangling reference. In Example B I get neither the warning nor the Segfault.

Tested on 2 machines so far.

  • Compiler 7.4.0 Ubuntu
  • Compiler 7.5.0 Ubuntu

This is quite puzzling. Might somebody know if this has any reason?

I want to be clear here: This is undefined behaviour. Yes, the program could theoretically do anything, even explode the world. This is not what I ask. The question is about why the compiler detects one case, and not the other. The fact that it seems to work reproducably in the case where there is also no warning could just be a coincidence or not. "This is undefined behavior" is not a satisfactory answer, as it answers only what the program is capable of doing and not why the compiler does not even detect this in this case.

Meph
  • 370
  • 1
  • 13
  • 1
    *This is quite puzzling* -- Undefined behavior. There is nothing puzzling about it. – PaulMcKenzie Nov 15 '20 at 01:33
  • 1
    Undefined behaviour means it could do anything, *including working as expected*, though you should not count on that being the case consistently. – tadman Nov 15 '20 at 01:39

0 Answers0