[solved] Segmentation fault and std::clog.rdbuf()

I'm getting a segmentation fault after main() returns:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <fstream>

int main(){
    std::ofstream logfile("log.txt");
    std::clog.rdbuf(logfile.rdbuf());
    std::clog <<"This is written to file."<<std::endl;
    logfile.close(); //I also tried removing this, but it had no effect.
    return 0;
}

Also, after a few times of failing, cout stops working, and efter a few more times, cout works again, but repeats its contents after the return (so cout <<1; cout <<2; outputs "1212").
Any idea?
Last edited on
Well, you forgot to reset the standard output buffer. Make a backup before you change it and reset it just before you close the logfile.

Before attaching the file stream:
std::streambuf* backup = std::clog.rdbuf();
Before closing the file stream:
std::clog.rdbuf(backup);

PS
You might want to change the topic of your post. "Segfault" isn't very helpful to anyone having the same problem. You also might, if the solution provided above does work, add a [solved]-tag to the subject line. It helps finding the posts one wants to read.
Last edited on
It worked. Thanks.
Topic archived. No new replies allowed.