Home > front end >  Segmentation fault with references
Segmentation fault with references

Time:07-28

Why do I get Segmentation fault with the code below?

#include <iostream>
#include <string>

const std::string& f() { return "abc"; }
std::string&& g() { return "xyz"; }

int main()
{
    const std::string& s1 = f();

    std::string&& s2 = g();

    s2  = "-uvw";

    std::cout << s1 << ", " << s2 << std::endl;

    return 0;
}

I expected that both s1 and s2 are still alive with I print them, but actually they are not. Why?

For example, they are alive in the code below that does not crash:

#include <iostream>
#include <string>

int main()
{
    const std::string& s1 = "abc";

    std::string&& s2 = "xyz";

    s2  = "-uvw";

    std::cout << s1 << ", " << s2 << std::endl;

    return 0;
}

what is the difference?

CodePudding user response:

Your second example with no extra function calls is well-defined due to the reference lifetime extension rules. Essentially, when a prvalue is immediately bound to a reference upon creation, the lifetime of the referenced object is extended to that of the reference.

In your first example, reference lifetime extension does not apply. The prvalues created in your functions' return statements are not immediately bound to the references in main (there are intermediate steps). The objects referenced by the references returned by f and g are local to those functions, and immediately go out of scope when the function returns.

CodePudding user response:

You are creating temporary string objects on the stack. Once the function runs, the stack space is freed and you are holding an invalid reference. In the second example, the string is still stored in valid memory since the function has not returned yet.

  • Related