Segmentation fault with clog stream redirection

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?

Answers


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

Need Your Help

Query Maxmind GeoLite2 City Blocks csv in SQL Server to get geoname_id for IPv6 and IPv4 addresses

sql-server tsql ipv6 ipv4 maxmind

Maxmind has two free GeoLite2 cvs files that we can use to look up locations associated with IP address ranges. I want to create a stored proc in SQL Server that uses the imported tables

Flex Upload XML to datagrid/database

xml flex datagrid upload arraycollection

We have an requirement in our project to browse &amp; upload an XML file and show it on the datagrid, edit the grid and then save the contents to the database. I'm able to see examples that take a ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.