title: Simple Boost UDP receiver gest heap-use-after-free when using std::vector
body: <p>I am struggeling to understand why my quite simple UDP receiver is getting heap-free-after-use error (diagnosed by ASAN). The idea is listen to a configurable number of local ports for incoming packets.</p>
  <p>I am here posting a simplified version of the class</p>
  <p>UdpReceiver.hpp</p>
  <pre><code>class UdpReceiver
  {
    public:
      UdpReceiver(std::vector&lt;int&gt; listen_ports);
      void run();
    protected:
      boost::asio::io_service m_io;
      char m_receive_buffer[MAX_RECEIVE_LENGTH];
      std::vector&lt;udp::endpoint&gt; m_endpoints;
      std::vector&lt;udp::socket&gt; m_sockets;
      void handleUdpData(const boost::system::error_code&amp; error, size_t bytes_recvd, int idx);
  
  }; 
  </code></pre>
  <p>UdpReceiver.cpp</p>
  <pre><code>UdpReceiver::UdpReceiver(std::vector&lt;int&gt; listen_ports) : 
    m_io()
  { 
    
    int idx = 0;
    try {
    for (auto port: listen_ports) {
      m_endpoints.push_back(udp::endpoint(udp::v4(), port));
      m_sockets.push_back(udp::socket(m_io, m_endpoints[idx]));
      m_sockets[idx].async_receive_from(
        boost::asio::buffer(m_receive_buffer, MAX_RECEIVE_LENGTH), m_endpoints[idx],
        boost::bind(&amp;MessageParser::handleUdpData, this,
        boost::asio::placeholders::error,
        boost::asio::placeholders::bytes_transferred,
        idx)
      );
      idx++;
    }
    } catch(const std::exception &amp;exc) 
    {
      std::cerr &lt;&lt;exc.what();
      exit(-1);
    }
  }
  </code></pre>
  <p>According to ASAN m_endpoints.push_back(udp::endpoint(udp::v4(), port)) allocates some dynamic memory which is again freed by a later iteration. This eventually gives me use-after-free which messes up my application in a unpredictable way.</p>
  <p>I cant really understand how the use of std::vector should not work in this case. Any ideas?</p>