2011-02-11 137 views
5

我遇到过使用asio :: streambuf的问题,并且希望有人可以告诉我,如果我错误地使用了类。当我运行这个示例代码时,它会出现段错误。为什么?使用boost :: 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; 
} 
+0

可能的错误... – niXman 2011-02-12 08:51:04

+0

这只是`asio :: streambuf`,或者`std :: streambuf`表现出相同的行为吗? – 2011-02-18 15:32:16

回答

1

我已经使用和ASIO看到::流缓冲通常使用的方法是使用的std :: ostream的或std :: istream的,是这样的:

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

我不知道为什么你的代码无法正常工作,但如果上述功能正常工作,则通过它可能会显示与您的代码不同的一些区别。还有哪条线路崩溃?

相关问题