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?

4

1 回答 1

1

你需要恢复以前的rdbuf 你可以这样做

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();
于 2013-05-02T23:34:00.460 回答