Boost logo

Boost Users :

Subject: [Boost-users] Heap vs. Stack allocation of filtering_streambuf??
From: Eric R George (Eric.R.George_at_[hidden])
Date: 2009-11-19 12:44:52


Hi Folks - I'm working on a mod to an existing program to write compressed
output files. The following code works fine, but if I put the indicated
code in a function, it drops core when I attempt to write to the ofile
ostream - presumably because the filtering_streambuf<output> out was
allocated on the stack and no longer exists after the function exits.

#include <fstream>
#include <iostream>
#include <string>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/bzip2.hpp>

using namespace std;
using namespace boost::iostreams;
using namespace boost::iostreams::bzip2;

int main()
{
 string x;

 fstream infile;
 infile.open("00011.eph.org", ios::in);

 ostream *ofile;

//******* To be put in function ************************
 fstream *file2;
 file2 = new fstream;
 file2->open("00011.eph.org.bz2", ios_base::out | ios_base::binary);

 filtering_streambuf<output> out;
 out.push(bzip2_compressor());
 out.push(*file2);

 ofile = new ostream(&out);
//******* To be put in function ************************

 while(!infile.eof())
    {
     getline(infile, x);
     *ofile << x << endl;
    }

 return 0;
}

//*****************************************************************************

Now if I attempt to dynamically allocate the filtering_streambuf.

#include <fstream>
#include <iostream>
#include <string>
#include <boost/iostreams/filtering_streambuf.hpp>
#include <boost/iostreams/filter/bzip2.hpp>

using namespace std;
using namespace boost::iostreams;
using namespace boost::iostreams::bzip2;

int main()
{
 string x;

 fstream infile;
 infile.open("00011.eph.org", ios::in);

 ostream *ofile;

//******* To be put in function ************************
 fstream *file2;
 file2 = new fstream;
 file2->open("00011.eph.org.bz2", ios_base::out | ios_base::binary);

 filtering_streambuf<output> *out;
 out = new filtering_streambuf<output>;
 out->push(bzip2_compressor());
 out->push(*file2);

 ofile = new ostream(out);
//******* To be put in function ************************

 while(!infile.eof())
    {
     getline(infile, x);
     *ofile << x << endl;
    }

 return 0;
}

This code compiles and runs fine, but the compressed output file,
00011.eph.org.bz2, ends up empty. Moving the indicated code to a function
again works fine - but again, no output??

The reasoning for all this is that I'd like to be able to open and set up
the various output streams in a function, and then pass those streams
around as needed. Which means they need to be dynamically allocated/built
on the heap. But it's not working??

Ideas? What am I missing here?
Thanks
Eric



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