Search code examples
c++referencesegmentation-faultc++17rvalue-reference

R-value reference to a temporary object does not segfault


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.


Solution

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