【问题标题】:Code using boost::asio::streambuf causes segfault使用 boost::asio::streambuf 的代码会导致段错误
【发布时间】:2011-02-11 17:14:39
【问题描述】:

我在使用 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;
}

【问题讨论】:

  • 这只是asio::streambuf,还是std::streambuf 表现出相同的行为?
  • 我也得到了核心转储。请#include &lt;iostream&gt; 编译代码。
  • Clang on OS X Mavericks 编译并运行成功,产生1\n0\n 作为输出。
  • 我也遇到过同样的问题。我用 clang++ 而不是 g++ 编译了我的程序,一切都按预期工作。

标签: c++ boost boost-asio streambuf


【解决方案1】:

我使用和看到的 asio::streambuf 通常使用的方式是使用 std::ostream 或 std::istream,类似于:

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

我不确定为什么您的代码不起作用,但如果上述方法起作用,那么单步执行它可能会与您的代码有所不同。还有它在哪一行崩溃?

【讨论】:

  • 代码在“下一行程序出现段错误”的注释后崩溃。
  • @DylanKlomparens:好的。我回答问题的时候有吗?有一阵子了。 :-) 听起来像是一个错误,您传递的大小不受尊重。
猜你喜欢
  • 1970-01-01
  • 2017-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多