首页 > 解决方案 > 带有 shared_ptr 的处理程序中的分段错误

问题描述

我正在尝试制作一个仅适用于应用程序执行中的第一个会话的代理。它SIGSEGV试图处理第二个。

它的工作方式如下:

问题是当我们启动应用程序并且第一个客户端尝试使用代理时,它工作正常(让客户端始终连接到代理,例如第一个获取其数据,断开连接,然后第二个连接)。但是当第二个尝试在此之后连接时,执行甚至无法到达函数中的和捕获handleAccept(我在 Linux 中工作)。SIGSEGV__atomic_addatomicity.h

我无法理解我错误地制作处理程序,错误地使用shared_ptr's,或两者兼而有之。

run在创建对象后调用一次Proxy以使其接受并处理客户端连接:

void Proxy::run() // create the very first session and keep waiting for other connections
{
    auto newSession = std::make_shared<Session>(ioService_);

    acceptor_.async_accept(
        newSession->getClientSocket(),
        [&](const boost::system::error_code &error) // handler is made according to boost documentation
        {
            handleAccept(newSession, error);
        }
    );

    ioService_.run();
}

handleAccept做几乎相同的事情,但也使会话开始在客户端和端服务器之间传输数据:

void Proxy::handleAccept(std::shared_ptr<Session> session, const boost::system::error_code &error) // handle the new connection and keep waiting other ones
{
    if (!error)
    {
        session->connectToServer(serverEndpoint_);
        session->run(); // two more shared_ptr's to session are appeared here and we just let it go (details are further)
    }

    auto newSession = std::make_shared<Session>(ioService_);

    acceptor_.async_accept(
        newSession->getClientSocket(),
        [&](const boost::system::error_code &error)
        {
            handleAccept(newSession, error);
        }
    );
}

Session包含两个Socket对象(服务器和客户端),每个对象都有shared_ptr它。当他们每个人都将完成所有操作或发生某些错误时,他们resetshared_ptr进入会话,因此将其释放。

标签: c++boostshared-ptrgnu

解决方案


为什么你在 handleAccept(...) 中通过引用来使用/捕获局部变量?:

 acceptor_.async_accept(
        newSession->getClientSocket(),
        [&](const boost::system::error_code &error)
        {
            handleAccept(newSession, error);
        }
    );

您想使用:

 acceptor_.async_accept(
        newSession->getClientSocket(),
        [this, newSession](const boost::system::error_code &error)
        {
            handleAccept(newSession, error);
        }
    );

lambda 将在函数完成后运行,并且在此之前局部变量 newSession 将被销毁。


推荐阅读