C++ Boost.Asio Segmentation Fault on async_write while accessing write-method through shared_ptr





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I created a static map that holds several Sessions of connected clients.



std::map<std::string, std::shared_ptr<Session>> Communication::m_appSockets;


The Listener that accepts incomming clients is implemented in the Communication class.



class Communication : public std::enable_shared_from_this<Communication>
{
private:
boost::asio::io_context m_ioc;
boost::asio::io_context::work m_work;
boost::asio::streambuf m_buffer;
boost::asio::ip::tcp::acceptor m_acceptor;
std::thread m_senderThread;
std::thread m_ioThread;

public:
static std::map<std::string, std::shared_ptr<Session>> m_appSockets;

Communication(uint16_t t_port);

void accept();

void doAccept();

void senderThread();
};


After accepting a client the method "doAccept" creates a session object and moves the socket like this



  m_acceptor.async_accept(
[this](boost::system::error_code t_ec, boost::asio::ip::tcp::socket t_socket) {
if (!t_ec)
{
m_appSockets.emplace(std::pair<std::string, std::shared_ptr<Session>>(
"app0", std::make_shared<Session>(std::move(t_socket))));
m_appSockets["app0"]->start();
}
accept();
});


Session.h looks like this:



class Session : public std::enable_shared_from_this<Session>
{
private:
boost::asio::ip::tcp::socket m_socket;
boost::asio::streambuf m_buffer;

public:

Session(boost::asio::ip::tcp::socket t_socket);

void write(std::string &t_msg);
void doWrite(std::string &t_msg);
void start();
...
};


void start() is used for starting the async read on the socket, which is working fine.
A session object is created this way:



Session::Session(boost::asio::ip::tcp::socket t_socket) : m_socket(std::move(t_socket))
{}


What I need to do for my implementation is to access the write-method of session through the shared_ptr in the map of Communication.h.
I tried it the following way



void Communication::senderThread()
{
for (;;)
{
....
//blocking until queue holds a message
std::string buf = *message from queue*//pseudo code
m_appSockets["app0"].get()->write(buf);

}
}


A senderthread blocks until a message is available in a queue which will be forwarded to the write method of session



The write-method can be called but as soon as i try an operation on any member of the session it gives me a segmentation fault:



void Session::write(std::string &t_msg)
{
//here it crashes
m_socket.get_executor().context().post(std::bind(&Session::doWrite, shared_from_this(), t_msg));
}

void Session::doWrite(std::string &t_msg)
{
boost::asio::async_write(
m_socket, boost::asio::buffer(t_msg),
std::bind(&Session::onWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
}


It feels like the Session object runs out of scope as soon as I enter its method. I have tried creating dummy members in Session which all gave the same segmentation fault when accessing them.
Am I getting the shared_ptr/object lifetime wrong at some point?



Thank you very much in advance.



EDIT 1:
Running gdb ./programm.out core gave me this:




Thread 2 "programm.out" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff58f1700 (LWP 5651)] 0x0000555555605932 in
Session::write (this=0x0,
t_msg="{"destination":"app0"}")
at /usr/Sources/Session.cpp:58 58 std::cout << dummyMember << std::endl;




I added a member to Session (int dummyMember{5};).



How can it be that this is pointing to 0x0?










share|improve this question































    0















    I created a static map that holds several Sessions of connected clients.



    std::map<std::string, std::shared_ptr<Session>> Communication::m_appSockets;


    The Listener that accepts incomming clients is implemented in the Communication class.



    class Communication : public std::enable_shared_from_this<Communication>
    {
    private:
    boost::asio::io_context m_ioc;
    boost::asio::io_context::work m_work;
    boost::asio::streambuf m_buffer;
    boost::asio::ip::tcp::acceptor m_acceptor;
    std::thread m_senderThread;
    std::thread m_ioThread;

    public:
    static std::map<std::string, std::shared_ptr<Session>> m_appSockets;

    Communication(uint16_t t_port);

    void accept();

    void doAccept();

    void senderThread();
    };


    After accepting a client the method "doAccept" creates a session object and moves the socket like this



      m_acceptor.async_accept(
    [this](boost::system::error_code t_ec, boost::asio::ip::tcp::socket t_socket) {
    if (!t_ec)
    {
    m_appSockets.emplace(std::pair<std::string, std::shared_ptr<Session>>(
    "app0", std::make_shared<Session>(std::move(t_socket))));
    m_appSockets["app0"]->start();
    }
    accept();
    });


    Session.h looks like this:



    class Session : public std::enable_shared_from_this<Session>
    {
    private:
    boost::asio::ip::tcp::socket m_socket;
    boost::asio::streambuf m_buffer;

    public:

    Session(boost::asio::ip::tcp::socket t_socket);

    void write(std::string &t_msg);
    void doWrite(std::string &t_msg);
    void start();
    ...
    };


    void start() is used for starting the async read on the socket, which is working fine.
    A session object is created this way:



    Session::Session(boost::asio::ip::tcp::socket t_socket) : m_socket(std::move(t_socket))
    {}


    What I need to do for my implementation is to access the write-method of session through the shared_ptr in the map of Communication.h.
    I tried it the following way



    void Communication::senderThread()
    {
    for (;;)
    {
    ....
    //blocking until queue holds a message
    std::string buf = *message from queue*//pseudo code
    m_appSockets["app0"].get()->write(buf);

    }
    }


    A senderthread blocks until a message is available in a queue which will be forwarded to the write method of session



    The write-method can be called but as soon as i try an operation on any member of the session it gives me a segmentation fault:



    void Session::write(std::string &t_msg)
    {
    //here it crashes
    m_socket.get_executor().context().post(std::bind(&Session::doWrite, shared_from_this(), t_msg));
    }

    void Session::doWrite(std::string &t_msg)
    {
    boost::asio::async_write(
    m_socket, boost::asio::buffer(t_msg),
    std::bind(&Session::onWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
    }


    It feels like the Session object runs out of scope as soon as I enter its method. I have tried creating dummy members in Session which all gave the same segmentation fault when accessing them.
    Am I getting the shared_ptr/object lifetime wrong at some point?



    Thank you very much in advance.



    EDIT 1:
    Running gdb ./programm.out core gave me this:




    Thread 2 "programm.out" received signal SIGSEGV, Segmentation fault.
    [Switching to Thread 0x7ffff58f1700 (LWP 5651)] 0x0000555555605932 in
    Session::write (this=0x0,
    t_msg="{"destination":"app0"}")
    at /usr/Sources/Session.cpp:58 58 std::cout << dummyMember << std::endl;




    I added a member to Session (int dummyMember{5};).



    How can it be that this is pointing to 0x0?










    share|improve this question



























      0












      0








      0








      I created a static map that holds several Sessions of connected clients.



      std::map<std::string, std::shared_ptr<Session>> Communication::m_appSockets;


      The Listener that accepts incomming clients is implemented in the Communication class.



      class Communication : public std::enable_shared_from_this<Communication>
      {
      private:
      boost::asio::io_context m_ioc;
      boost::asio::io_context::work m_work;
      boost::asio::streambuf m_buffer;
      boost::asio::ip::tcp::acceptor m_acceptor;
      std::thread m_senderThread;
      std::thread m_ioThread;

      public:
      static std::map<std::string, std::shared_ptr<Session>> m_appSockets;

      Communication(uint16_t t_port);

      void accept();

      void doAccept();

      void senderThread();
      };


      After accepting a client the method "doAccept" creates a session object and moves the socket like this



        m_acceptor.async_accept(
      [this](boost::system::error_code t_ec, boost::asio::ip::tcp::socket t_socket) {
      if (!t_ec)
      {
      m_appSockets.emplace(std::pair<std::string, std::shared_ptr<Session>>(
      "app0", std::make_shared<Session>(std::move(t_socket))));
      m_appSockets["app0"]->start();
      }
      accept();
      });


      Session.h looks like this:



      class Session : public std::enable_shared_from_this<Session>
      {
      private:
      boost::asio::ip::tcp::socket m_socket;
      boost::asio::streambuf m_buffer;

      public:

      Session(boost::asio::ip::tcp::socket t_socket);

      void write(std::string &t_msg);
      void doWrite(std::string &t_msg);
      void start();
      ...
      };


      void start() is used for starting the async read on the socket, which is working fine.
      A session object is created this way:



      Session::Session(boost::asio::ip::tcp::socket t_socket) : m_socket(std::move(t_socket))
      {}


      What I need to do for my implementation is to access the write-method of session through the shared_ptr in the map of Communication.h.
      I tried it the following way



      void Communication::senderThread()
      {
      for (;;)
      {
      ....
      //blocking until queue holds a message
      std::string buf = *message from queue*//pseudo code
      m_appSockets["app0"].get()->write(buf);

      }
      }


      A senderthread blocks until a message is available in a queue which will be forwarded to the write method of session



      The write-method can be called but as soon as i try an operation on any member of the session it gives me a segmentation fault:



      void Session::write(std::string &t_msg)
      {
      //here it crashes
      m_socket.get_executor().context().post(std::bind(&Session::doWrite, shared_from_this(), t_msg));
      }

      void Session::doWrite(std::string &t_msg)
      {
      boost::asio::async_write(
      m_socket, boost::asio::buffer(t_msg),
      std::bind(&Session::onWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
      }


      It feels like the Session object runs out of scope as soon as I enter its method. I have tried creating dummy members in Session which all gave the same segmentation fault when accessing them.
      Am I getting the shared_ptr/object lifetime wrong at some point?



      Thank you very much in advance.



      EDIT 1:
      Running gdb ./programm.out core gave me this:




      Thread 2 "programm.out" received signal SIGSEGV, Segmentation fault.
      [Switching to Thread 0x7ffff58f1700 (LWP 5651)] 0x0000555555605932 in
      Session::write (this=0x0,
      t_msg="{"destination":"app0"}")
      at /usr/Sources/Session.cpp:58 58 std::cout << dummyMember << std::endl;




      I added a member to Session (int dummyMember{5};).



      How can it be that this is pointing to 0x0?










      share|improve this question
















      I created a static map that holds several Sessions of connected clients.



      std::map<std::string, std::shared_ptr<Session>> Communication::m_appSockets;


      The Listener that accepts incomming clients is implemented in the Communication class.



      class Communication : public std::enable_shared_from_this<Communication>
      {
      private:
      boost::asio::io_context m_ioc;
      boost::asio::io_context::work m_work;
      boost::asio::streambuf m_buffer;
      boost::asio::ip::tcp::acceptor m_acceptor;
      std::thread m_senderThread;
      std::thread m_ioThread;

      public:
      static std::map<std::string, std::shared_ptr<Session>> m_appSockets;

      Communication(uint16_t t_port);

      void accept();

      void doAccept();

      void senderThread();
      };


      After accepting a client the method "doAccept" creates a session object and moves the socket like this



        m_acceptor.async_accept(
      [this](boost::system::error_code t_ec, boost::asio::ip::tcp::socket t_socket) {
      if (!t_ec)
      {
      m_appSockets.emplace(std::pair<std::string, std::shared_ptr<Session>>(
      "app0", std::make_shared<Session>(std::move(t_socket))));
      m_appSockets["app0"]->start();
      }
      accept();
      });


      Session.h looks like this:



      class Session : public std::enable_shared_from_this<Session>
      {
      private:
      boost::asio::ip::tcp::socket m_socket;
      boost::asio::streambuf m_buffer;

      public:

      Session(boost::asio::ip::tcp::socket t_socket);

      void write(std::string &t_msg);
      void doWrite(std::string &t_msg);
      void start();
      ...
      };


      void start() is used for starting the async read on the socket, which is working fine.
      A session object is created this way:



      Session::Session(boost::asio::ip::tcp::socket t_socket) : m_socket(std::move(t_socket))
      {}


      What I need to do for my implementation is to access the write-method of session through the shared_ptr in the map of Communication.h.
      I tried it the following way



      void Communication::senderThread()
      {
      for (;;)
      {
      ....
      //blocking until queue holds a message
      std::string buf = *message from queue*//pseudo code
      m_appSockets["app0"].get()->write(buf);

      }
      }


      A senderthread blocks until a message is available in a queue which will be forwarded to the write method of session



      The write-method can be called but as soon as i try an operation on any member of the session it gives me a segmentation fault:



      void Session::write(std::string &t_msg)
      {
      //here it crashes
      m_socket.get_executor().context().post(std::bind(&Session::doWrite, shared_from_this(), t_msg));
      }

      void Session::doWrite(std::string &t_msg)
      {
      boost::asio::async_write(
      m_socket, boost::asio::buffer(t_msg),
      std::bind(&Session::onWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
      }


      It feels like the Session object runs out of scope as soon as I enter its method. I have tried creating dummy members in Session which all gave the same segmentation fault when accessing them.
      Am I getting the shared_ptr/object lifetime wrong at some point?



      Thank you very much in advance.



      EDIT 1:
      Running gdb ./programm.out core gave me this:




      Thread 2 "programm.out" received signal SIGSEGV, Segmentation fault.
      [Switching to Thread 0x7ffff58f1700 (LWP 5651)] 0x0000555555605932 in
      Session::write (this=0x0,
      t_msg="{"destination":"app0"}")
      at /usr/Sources/Session.cpp:58 58 std::cout << dummyMember << std::endl;




      I added a member to Session (int dummyMember{5};).



      How can it be that this is pointing to 0x0?







      c++ segmentation-fault boost-asio shared-ptr






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 '18 at 13:19







      UltraGeralt

















      asked Nov 22 '18 at 9:44









      UltraGeraltUltraGeralt

      32




      32
























          1 Answer
          1






          active

          oldest

          votes


















          2














          Below line is suspicious



            boost::asio::buffer(t_msg)


          asio::buffer returns object which holds a pointer to the content of string and length of string (a copy of t_msg is not created). You have to be careful when using asio::buffer with asynchronous operations because its return type is pair (pointer,length) to string, it doesn't extend the lifetime of string.



          async_write function returns immediately and we don't know when handler will be called, so you have to make sure that msg is valid until handler is called.



            for(;;)
          {
          std::string buf = *message from queue*//pseudo code
          m_appSockets["app0"].get()->write(buf);

          // if you want to send original buf string
          // before this loop ends all asynchronous operation writing buf must be complete
          }


          If your goal is to send msg you have missed to use ref wrapper, because bind takes parameters by value by default.



          std::bind(&Session::doWrite, shared_from_this(), t_msg) // make copy of t_msg


          above creates callback which holds copy of t_msg.
          When this callback is called copy of t_msg is passed into boost::asio::buffer(t_msg) in Session::doWrite. Probably, before callback created by std::bind(&Session::onWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2) is executed string copy is destroyed and buffer points to deleted data.



          You can rewrite Session::write method using std::ref:



          m_socket.get_executor().context().post(std::bind(&Session::doWrite, shared_from_this(), std::ref(t_msg)));


          and ensure that all asynchronous operations which write this string are complete until for loop ends in senderThread. Or you need to find another way to hold t_msg string while asynchronous operations are executed.






          share|improve this answer


























          • Thank you very much for your answer. Indeed this is a problem I have. I adapted my code but this doesn't fix the segmentation fault. The error occurs already in in write() before doWrite() is reached. For example: If I add a member int dummy{5}; to session and try access it through a getter method at the beginning of write() I already get the segmentation fault.

            – UltraGeralt
            Nov 22 '18 at 10:49






          • 1





            Thanks for your answer which would have let to mistakes later on. I accessed the map in a seperate thread before the async accept created the session in the map, as we got the "this" pointing to 0x0 in the core dump. Making sure the object is created first fixed the problem.

            – UltraGeralt
            Nov 22 '18 at 13:42












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53427997%2fc-boost-asio-segmentation-fault-on-async-write-while-accessing-write-method-th%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          Below line is suspicious



            boost::asio::buffer(t_msg)


          asio::buffer returns object which holds a pointer to the content of string and length of string (a copy of t_msg is not created). You have to be careful when using asio::buffer with asynchronous operations because its return type is pair (pointer,length) to string, it doesn't extend the lifetime of string.



          async_write function returns immediately and we don't know when handler will be called, so you have to make sure that msg is valid until handler is called.



            for(;;)
          {
          std::string buf = *message from queue*//pseudo code
          m_appSockets["app0"].get()->write(buf);

          // if you want to send original buf string
          // before this loop ends all asynchronous operation writing buf must be complete
          }


          If your goal is to send msg you have missed to use ref wrapper, because bind takes parameters by value by default.



          std::bind(&Session::doWrite, shared_from_this(), t_msg) // make copy of t_msg


          above creates callback which holds copy of t_msg.
          When this callback is called copy of t_msg is passed into boost::asio::buffer(t_msg) in Session::doWrite. Probably, before callback created by std::bind(&Session::onWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2) is executed string copy is destroyed and buffer points to deleted data.



          You can rewrite Session::write method using std::ref:



          m_socket.get_executor().context().post(std::bind(&Session::doWrite, shared_from_this(), std::ref(t_msg)));


          and ensure that all asynchronous operations which write this string are complete until for loop ends in senderThread. Or you need to find another way to hold t_msg string while asynchronous operations are executed.






          share|improve this answer


























          • Thank you very much for your answer. Indeed this is a problem I have. I adapted my code but this doesn't fix the segmentation fault. The error occurs already in in write() before doWrite() is reached. For example: If I add a member int dummy{5}; to session and try access it through a getter method at the beginning of write() I already get the segmentation fault.

            – UltraGeralt
            Nov 22 '18 at 10:49






          • 1





            Thanks for your answer which would have let to mistakes later on. I accessed the map in a seperate thread before the async accept created the session in the map, as we got the "this" pointing to 0x0 in the core dump. Making sure the object is created first fixed the problem.

            – UltraGeralt
            Nov 22 '18 at 13:42
















          2














          Below line is suspicious



            boost::asio::buffer(t_msg)


          asio::buffer returns object which holds a pointer to the content of string and length of string (a copy of t_msg is not created). You have to be careful when using asio::buffer with asynchronous operations because its return type is pair (pointer,length) to string, it doesn't extend the lifetime of string.



          async_write function returns immediately and we don't know when handler will be called, so you have to make sure that msg is valid until handler is called.



            for(;;)
          {
          std::string buf = *message from queue*//pseudo code
          m_appSockets["app0"].get()->write(buf);

          // if you want to send original buf string
          // before this loop ends all asynchronous operation writing buf must be complete
          }


          If your goal is to send msg you have missed to use ref wrapper, because bind takes parameters by value by default.



          std::bind(&Session::doWrite, shared_from_this(), t_msg) // make copy of t_msg


          above creates callback which holds copy of t_msg.
          When this callback is called copy of t_msg is passed into boost::asio::buffer(t_msg) in Session::doWrite. Probably, before callback created by std::bind(&Session::onWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2) is executed string copy is destroyed and buffer points to deleted data.



          You can rewrite Session::write method using std::ref:



          m_socket.get_executor().context().post(std::bind(&Session::doWrite, shared_from_this(), std::ref(t_msg)));


          and ensure that all asynchronous operations which write this string are complete until for loop ends in senderThread. Or you need to find another way to hold t_msg string while asynchronous operations are executed.






          share|improve this answer


























          • Thank you very much for your answer. Indeed this is a problem I have. I adapted my code but this doesn't fix the segmentation fault. The error occurs already in in write() before doWrite() is reached. For example: If I add a member int dummy{5}; to session and try access it through a getter method at the beginning of write() I already get the segmentation fault.

            – UltraGeralt
            Nov 22 '18 at 10:49






          • 1





            Thanks for your answer which would have let to mistakes later on. I accessed the map in a seperate thread before the async accept created the session in the map, as we got the "this" pointing to 0x0 in the core dump. Making sure the object is created first fixed the problem.

            – UltraGeralt
            Nov 22 '18 at 13:42














          2












          2








          2







          Below line is suspicious



            boost::asio::buffer(t_msg)


          asio::buffer returns object which holds a pointer to the content of string and length of string (a copy of t_msg is not created). You have to be careful when using asio::buffer with asynchronous operations because its return type is pair (pointer,length) to string, it doesn't extend the lifetime of string.



          async_write function returns immediately and we don't know when handler will be called, so you have to make sure that msg is valid until handler is called.



            for(;;)
          {
          std::string buf = *message from queue*//pseudo code
          m_appSockets["app0"].get()->write(buf);

          // if you want to send original buf string
          // before this loop ends all asynchronous operation writing buf must be complete
          }


          If your goal is to send msg you have missed to use ref wrapper, because bind takes parameters by value by default.



          std::bind(&Session::doWrite, shared_from_this(), t_msg) // make copy of t_msg


          above creates callback which holds copy of t_msg.
          When this callback is called copy of t_msg is passed into boost::asio::buffer(t_msg) in Session::doWrite. Probably, before callback created by std::bind(&Session::onWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2) is executed string copy is destroyed and buffer points to deleted data.



          You can rewrite Session::write method using std::ref:



          m_socket.get_executor().context().post(std::bind(&Session::doWrite, shared_from_this(), std::ref(t_msg)));


          and ensure that all asynchronous operations which write this string are complete until for loop ends in senderThread. Or you need to find another way to hold t_msg string while asynchronous operations are executed.






          share|improve this answer















          Below line is suspicious



            boost::asio::buffer(t_msg)


          asio::buffer returns object which holds a pointer to the content of string and length of string (a copy of t_msg is not created). You have to be careful when using asio::buffer with asynchronous operations because its return type is pair (pointer,length) to string, it doesn't extend the lifetime of string.



          async_write function returns immediately and we don't know when handler will be called, so you have to make sure that msg is valid until handler is called.



            for(;;)
          {
          std::string buf = *message from queue*//pseudo code
          m_appSockets["app0"].get()->write(buf);

          // if you want to send original buf string
          // before this loop ends all asynchronous operation writing buf must be complete
          }


          If your goal is to send msg you have missed to use ref wrapper, because bind takes parameters by value by default.



          std::bind(&Session::doWrite, shared_from_this(), t_msg) // make copy of t_msg


          above creates callback which holds copy of t_msg.
          When this callback is called copy of t_msg is passed into boost::asio::buffer(t_msg) in Session::doWrite. Probably, before callback created by std::bind(&Session::onWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2) is executed string copy is destroyed and buffer points to deleted data.



          You can rewrite Session::write method using std::ref:



          m_socket.get_executor().context().post(std::bind(&Session::doWrite, shared_from_this(), std::ref(t_msg)));


          and ensure that all asynchronous operations which write this string are complete until for loop ends in senderThread. Or you need to find another way to hold t_msg string while asynchronous operations are executed.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 22 '18 at 10:40

























          answered Nov 22 '18 at 10:31









          rafix07rafix07

          8,4731916




          8,4731916













          • Thank you very much for your answer. Indeed this is a problem I have. I adapted my code but this doesn't fix the segmentation fault. The error occurs already in in write() before doWrite() is reached. For example: If I add a member int dummy{5}; to session and try access it through a getter method at the beginning of write() I already get the segmentation fault.

            – UltraGeralt
            Nov 22 '18 at 10:49






          • 1





            Thanks for your answer which would have let to mistakes later on. I accessed the map in a seperate thread before the async accept created the session in the map, as we got the "this" pointing to 0x0 in the core dump. Making sure the object is created first fixed the problem.

            – UltraGeralt
            Nov 22 '18 at 13:42



















          • Thank you very much for your answer. Indeed this is a problem I have. I adapted my code but this doesn't fix the segmentation fault. The error occurs already in in write() before doWrite() is reached. For example: If I add a member int dummy{5}; to session and try access it through a getter method at the beginning of write() I already get the segmentation fault.

            – UltraGeralt
            Nov 22 '18 at 10:49






          • 1





            Thanks for your answer which would have let to mistakes later on. I accessed the map in a seperate thread before the async accept created the session in the map, as we got the "this" pointing to 0x0 in the core dump. Making sure the object is created first fixed the problem.

            – UltraGeralt
            Nov 22 '18 at 13:42

















          Thank you very much for your answer. Indeed this is a problem I have. I adapted my code but this doesn't fix the segmentation fault. The error occurs already in in write() before doWrite() is reached. For example: If I add a member int dummy{5}; to session and try access it through a getter method at the beginning of write() I already get the segmentation fault.

          – UltraGeralt
          Nov 22 '18 at 10:49





          Thank you very much for your answer. Indeed this is a problem I have. I adapted my code but this doesn't fix the segmentation fault. The error occurs already in in write() before doWrite() is reached. For example: If I add a member int dummy{5}; to session and try access it through a getter method at the beginning of write() I already get the segmentation fault.

          – UltraGeralt
          Nov 22 '18 at 10:49




          1




          1





          Thanks for your answer which would have let to mistakes later on. I accessed the map in a seperate thread before the async accept created the session in the map, as we got the "this" pointing to 0x0 in the core dump. Making sure the object is created first fixed the problem.

          – UltraGeralt
          Nov 22 '18 at 13:42





          Thanks for your answer which would have let to mistakes later on. I accessed the map in a seperate thread before the async accept created the session in the map, as we got the "this" pointing to 0x0 in the core dump. Making sure the object is created first fixed the problem.

          – UltraGeralt
          Nov 22 '18 at 13:42




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53427997%2fc-boost-asio-segmentation-fault-on-async-write-while-accessing-write-method-th%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

          ComboBox Display Member on multiple fields

          Is it possible to collect Nectar points via Trainline?