1

This is a very trimmed down version of a code I am working with. I have trimmed the original code down to these few lines in an effort to isolate a segmentation fault I am getting at the end of program run.

#include <iostream>
#include <fstream>
#include <string>

int main(int argc, char *argv[]) {
    std::string cerr_file("cerr.out");
    std::string clog_file("clog.out");

    std::ofstream clogstream(clog_file, std::ofstream::out);
    std::ofstream cerrstream(cerr_file, std::ofstream::out);

    std::clog.rdbuf(clogstream.rdbuf());
    std::cerr.rdbuf(cerrstream.rdbuf());

    std::clog<<"Logging to clog"<<std::endl;

    clogstream.close();
    cerrstream.close();
}

When I compile this with g++ -m64 -O3 -std=c++11 test.cc -o test and run the binary I get a seg fault. I don't see why that should be the case. To make matters more frustrating if I compile the same code with g++ -m64 -std=c++11 test.cc -o test i no longer get the seg fault. Why is the optimization causing a problem? And what is the possible source of the problem?

deepak
  • 2,045
  • 2
  • 21
  • 36

1 Answers1

1

You need to restore the previous rdbuf you can do it like this

std::string cerr_file("cerr.out");
std::string clog_file("clog.out");

std::ofstream clogstream(clog_file, std::ofstream::out);
std::ofstream cerrstream(cerr_file, std::ofstream::out);

std::streambuf* prevclogbuf = std::clog.rdbuf(clogstream.rdbuf());
std::streambuf* prevcerrbuf = std::cerr.rdbuf(cerrstream.rdbuf());

std::clog<<"Logging to clog"<<std::endl;

// Restore the previous streambuf
std::clog.rdbuf(prevclogbuf);
std::cerr.rdbuf(prevcerrbuf);

clogstream.close();
cerrstream.close();
John Bandela
  • 2,416
  • 12
  • 19
  • clog and cerr delete their buffers in their destructors. Because clogstream/cerrstream have already deleted their buffers, you are double deleting. See http://stackoverflow.com/questions/14860267/whats-wrong-with-this-code Especially the last answer – John Bandela May 02 '13 at 23:44