0

I want to redirect std to a file. To do this, I wrote a class Foo, where I connect / disconnect the buffer in the writeToFilEnabled.

However, there is Segmentation fault. How is it correct?

#include <iostream>
#include <fstream>

class Foo {
public:
    Foo() {
        out.open("out.txt");
        coutbuf = std::cout.rdbuf();
    }
    
    void writeToFileEnabled(bool enabled) {
        if (enabled)
            std::cout.rdbuf(out.rdbuf());
        else
            std::cout.rdbuf(coutbuf);
    }
    
    void test(int a) {
        std::cout << a << "\n";
    }
private:
    std::ofstream out;
    std::streambuf * coutbuf;
};

int main()
{
    Foo foo;
    
    foo.test(1);
    foo.test(2);
    foo.writeToFileEnabled(true);
    
    foo.test(3);
    foo.test(4);
}
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52

1 Answers1

0

Your foo object is a local variable in the main function so when main returns, foo is destroyed and cout holds a pointer to your now-destroyed ofstream. When the program quits, the exit handlers try to destruct cout which causes it to accesses the invalid Foo::out object and crashes the program. You could try putting foo in the global scope or calling foo.writeToFileEnabled(false) at the end of the main function.