'Combine multiple boost::asio::const_buffer into a single buffer

My program receives data in the form of std::vector<boost::asio::const_buffer> buf_vect. I need to combine the const_buffer in the vector into a single buffer which will then be converted to a std::string for further processing.

First attempt:

size_t total_size = 0;
for (auto e : buf_vect) {
    total_size += e.size();
}
char* char_buf = new char[total_size];

for (auto e : buf_vect) {
    strncpy(char_buf, static_cast<const char*>(e.data()), e.size());
}
std::string data(char_buf, total_size);
delete char_buf;

// process data string

This attempt yields nonsense in the data string. Is this the correct approach or am I totally misunderstanding the behavior of buffers...?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source