阻塞流重定向的分段错误

Segmentation fault with clog stream redirection

本文关键字:分段 错误 重定向      更新时间:2023-10-16

这是我正在使用的一个非常精简的代码版本。我已经将原始代码缩减到这几行,以努力隔离我在程序运行结束时得到的分段错误。

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

您需要恢复之前的rdf,但是您可以这样做

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