阻塞流重定向的分段错误

时间:2013-05-02 23:27:17

标签: c++ c

这是我正在使用的代码的精简版本。我已经将原始代码修剪为这几行,以便隔离我在程序运行结束时得到的分段错误。

#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();
}

当我用g++ -m64 -O3 -std=c++11 test.cc -o test编译它并运行二进制文件时,我得到一个seg错误。我不明白为什么会这样。如果我用g++ -m64 -std=c++11 test.cc -o test编译相同的代码,使事情更加令人沮丧,我不再得到seg错误。为什么优化会导致问题?问题的可能来源是什么?

1 个答案:

答案 0 :(得分: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();