Zerox
Zerox

Reputation: 7

Boost asio, async_read error

Here is my code:

    void do_read_header()
    {
        std::string incoming_header;

        boost::asio::async_read(socket_, boost::asio::buffer(incoming_header, incoming_header.length()), [this, incoming_header](boost::system::error_code ec, std::size_t)
        {
            if (!ec && check_message(incoming_header))
            {
                do_read_body();
            }
            //else
            //{
            //  socket_.close();
            //}
        });
    }

    void do_read_body()
    {
        std::string incoming_message;

        boost::asio::async_read(socket_, boost::asio::buffer(incoming_message, incoming_message.length()), [this, incoming_message](boost::system::error_code ec, std::size_t)
        {
            if (!ec)
            {
                std::cout.write(incoming_message.c_str(), incoming_message.length());
                std::cout << "\n";
                //do_read_header();
            //}
            //else
            //{
                socket_.close();
            }
        });
    }

It's a modified version of this: http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/example/cpp11/chat/chat_client.cpp

What's wrong with my code?

Upvotes: 0

Views: 561

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254461

One problem is that the incoming_header and incoming_message are local variables, destroyed before the completion handler. You are capturing a copy of them while they're still empty; then the operation will write over freed memory, causing untold havoc.

One option, if you only need to read one message at a time, is to use a member variable rather than a local variable, and only capture this. Alternatively, you could allocate a buffer dynamically, remembering to delete it in the handler.

In any case, make sure you resize the buffer beforehand, or perhaps use boost::asio::streambuf to read arbitrary amounts. You are initialising the buffer with zero size, so you'd never get any data even if you didn't destroy the buffer.

Upvotes: 0

Related Questions