c++segmentation-fault

Why capture this in cpp in lambda and get reference to data member cause segfault?


#include <functional>
#include <string>
#include <iostream>



struct Info
{
    std::string a{"abc"};
};


struct Handlers
{
    std::function<const Info&()> get_info;
};

class A
{
    public:
    A()
    {
        handler_ = Handlers{
            .get_info = [this](){return data;}
        };
    };


    Info data;
    Handlers handler_;
};

int main()
{
    A a;
    std::string k = a.handler_.get_info().a;
    std::cout << k;
}

The above code segfault on std::string k = a.handler_.get_info().a;

with further investigation I found that std::cout << &a.handler_.get_info(); prints 0

I use following version of g++

g++ (Ubuntu 12.2.0-3ubuntu1) 12.2.0
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

and I compile the file with following command

g++  main.cpp --std=c++2a

Solution

  • Issue is that the lambda returns by value, whereas you expect to return reference according to std::function. Storing your lambda into the std::function makes the std::function return a dangling reference.

    Change to:

    [this]() -> Info& {return data;}
    

    Demo