阻塞流重定向的分段错误
Segmentation fault with clog stream redirection
这是我正在使用的一个非常精简的代码版本。我已经将原始代码缩减到这几行,以努力隔离我在程序运行结束时得到的分段错误。
#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();
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?