0

I was going over this stack overflow answer and I was trying out my own things for my understanding. In the answer, the author says in the line

auto&& __range=exp;

Your exp creates a temporary object, then returns a reference to within it. The temporary dies after that line, so you have a dangling reference in the rest of the code.

My understanding of this line: S() returns a temporary object of type S and .func() on it is returning a reference to this temporary object. Variable __range is pointing to a location that doesn't exist because the object of type S is destroyed by the end of that line.

So I wrote a similar program (below) with some modifications and was expecting it to SEGFAULT, but it does not SEGFAULT at all.

#include <iostream>
#include <string>
#include <map>
using namespace std;

struct S
{
    map<int, int> m;

    S()
    {
        m[24] = 5;
    }

    const int &func() const
    {
        return m.find(24)->second;
    }
};

int main()
{
    auto &&x = S().func();
    std::cout<<"\n value is "<<x;

    return 0;
}

I am not sure about the gaps in my understanding. Help me out. Thanks in advance.

user3219492
  • 774
  • 1
  • 10
  • 18
  • 2
    UB means anything is possible, it doesn't have to SEGFAULT. – songyuanyao Jun 21 '21 at 03:19
  • Please see https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior . When the behaviour is undefined there can be any consequences, you should not expect "segfault" or some other specific consequence – M.M Jun 21 '21 at 03:19
  • 1
    Echoing what @M.M said: You say (paraphrased) "I know this is undefined behavior, but I expect it to do *this*". Does that make the contradiction clearer? – Marshall Clow Jun 21 '21 at 04:02
  • 1
    UB aside, it can be helpful to understand why particular code executes a certain way, like doesn't crash. Think of segfault as consequence of dereferencing a bad memory address. But the address in particular case is not bad, just stale. – WilliamClements Jun 22 '21 at 16:35

2 Answers2

1

was expecting it to SEGFAULT

That's the mistake. There are no conditions in which the C++ language guarantees a segfault. In fact, the concept of a segfault is entirely foreign to the language itself.

According to the C++ language, the behaviour of your program is undefined. That means that anything could happen. Segfault could happen, but there are no guarantees that it will happen. There are no guarantees whatsoever about the behaviour of the program.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

If you build the program with address sanitizer, you get:

SUMMARY: AddressSanitizer: heap-use-after-free

At this line:

uto &&x = S().func();

Memory issues may not crash your program immediately, but they may crash a long-running program at other functions or other threads, lead to very weird crash scenarios.

prehistoricpenguin
  • 6,130
  • 3
  • 25
  • 42