Code using boost::asio::streambuf causes segfault

假装没事ソ 提交于 2019-12-12 10:47:05

问题


I've experienced problems using asio::streambuf and am hoping someone can tell me if I'm using the class incorrectly. When I run this example code it segfaults. Why?

To make things more confusing, this code works on Windows (Visual Studio 2008), but does not work on Linux (with gcc 4.4.1).

#include <boost/asio.hpp>
using namespace std;

int main()
{
        boost::asio::streambuf Stream;

        // Put 4 bytes into the streambuf...
        int SetValue = 0xaabbccdd;
        Stream.sputn(reinterpret_cast<const char*>(&SetValue), sizeof(SetValue));

        // Consume 3 of the bytes...
        Stream.consume(3);
        cout << Stream.size() << endl; // should output 1

        // Get the last byte...
        char GetValue;
        // --------- The next line segfaults the program ----------
        Stream.sgetn(reinterpret_cast<char*>(&GetValue), sizeof(GetValue));
        cout << Stream.size() << endl; // should output 0

        return 0;
}

回答1:


The way I've used and seen asio::streambuf usually used is with std::ostream or std::istream, something like:

boost::asio::streambuf Stream;
std::ostream os(&Stream);
int SetValue = 0xaabbccdd;
os.write(reinterpret_cast<const char*>(&SetValue), sizeof(SetValue));

I'm not sure why your code doesn't work but if the above does work then stepping through it may show some difference vs. your code. Also which line is it crashing on?



来源:https://stackoverflow.com/questions/4971980/code-using-boostasiostreambuf-causes-segfault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!