使用 boost::asio::streambuf 的代码会导致段错误
我在使用 asio::streambuf 时遇到了问题,希望有人能告诉我我是否错误地使用了该类。当我运行此示例代码时,它出现段错误。为什么?
更令人困惑的是,这段代码可以在 Windows (Visual Studio 2008) 上运行,但不能在 Linux (使用 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我使用和看到 asio::streambuf 通常使用的方式是与 std::ostream 或 std::istream 一起使用,例如:
我不确定为什么你的代码不起作用,但如果上面的代码确实有效,则逐步执行它可能与您的代码显示出一些差异。另外,它崩溃在哪一行?
The way I've used and seen asio::streambuf usually used is with std::ostream or std::istream, something like:
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?