Code using boost::asio::streambuf causes segfault
Asked Answered
S

1

6

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;
}
Subcontract answered 11/2, 2011 at 17:14 Comment(4)
is this just asio::streambuf, or does std::streambuf exhibit the same behavior?Hematite
I also got core dumped. please #include <iostream> to get you code compiled.Kendallkendell
Clang on OS X Mavericks compiled and ran successfully, producing 1\n0\n as output.Joshua
I've experienced the same issue. I compiled my program with clang++ instead of g++ and everything worked as expected.Kumamoto
R
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?

Runofthemine answered 7/3, 2011 at 3:39 Comment(2)
The code crashes after the comment that says "the next line segfaults the program".Subcontract
@DylanKlomparens: OK. Was that there when I answered the question? It's been a while. :-) Sounds like a bug where the size you're passing isn't respected.Runofthemine

© 2022 - 2024 — McMap. All rights reserved.