Boost logo

Boost Users :

Subject: Re: [Boost-users] [Iostreams] Segmentation fault when stream is flushed or closed
From: Slava (Viatcheslav.Sysoltsev_at_[hidden])
Date: 2013-11-25 06:43:56


On Mon, 25 Nov 2013 11:48:19 +0100, Steven Maenhout
<Steven.Maenhout_at_[hidden]> wrote:

> Hello,
>
> I'm trying to open a boost::iostreams::stream in the constructor of a
> class and to close the stream in the destructor. This works fine but
> when I pass a reference to a std::stringstream in that same constructor
> I get a segmentation fault in the destructor when I flush or close the
> stream. This happens irrespective if the passed std::stringstream
> reference takes part in the boost::iostream::stream or not.
>
> I'm using gcc 4.6.3 with boost 1.53 on Linux x86_64.
>
> Below I provided a small example that exhibits this behaviour.
>
> Any ideas anyone?
>
> #include "test.h"
>
> int main(int argc, char **argv) {
>
> std::stringstream logStream;
> Test test(logStream);
> return 0;
> }
>
> where test.h contains:
>
> #include <fstream>
> #include <sstream>
> #include <boost/iostreams/stream.hpp>
> #include <boost/iostreams/tee.hpp>
>
> typedef boost::iostreams::tee_device<std::stringstream, std::ofstream>
> TeeDevice;
> typedef boost::iostreams::stream<TeeDevice> TeeStream;
>
> class Test {
>
> public:
> Test(const std::stringstream& logStream) {
>
> std::ofstream dummyFileHandle("/dev/null", std::ios_base::out |
> std::ios_base::app);
> std::stringstream logStream2;
> TeeDevice myTee (logStream2, dummyFileHandle);
> m_out.open(myTee);
> }
> virtual ~Test() {
>
> if(m_out.is_open()) {
> m_out.flush();
> m_out.close();
> }
> };
> protected:
> TeeStream m_out;
> };

Hi Steven,

I don't know boost::iostream, but valgrind shows that failure occurs
because destructor attempts to dereference the memory, which was allocated
on the stack. Moving dummyFileHandle and logStream2 into global scope
fixes the crash. I guess, you cannot pass temporaries into TeeDevice
constructor and have to hold dummyFileHandle and logStream2 alive as long
as they are referenced in TeeDevice (making them class members accessed
through shared_ptr perhaps?).

Regards, Slava


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net