C++ exit(1) causes IO loss?

114 Views Asked by At

Here is my program:

#include <fstream>

int main() {
    std::ofstream fout("data.dat", std::ios::binary);
    for (int isam=0; isam<500; isam++) fout.write((char*) &isam, 4);
    exit(1);
}

When I run this on a MacBook, file data.dat is 1 byte long (on AWS, it's 0 bytes), not 2000. If I increase 500, I eventually get more bytes out, but never the expected amount. BUT, when I comment out the exit(), everything works as expected regardless of the number of bytes. It's as if exit() stops buffered output from the previous line of code. Isn't this a bug? Thanks

1

There are 1 best solutions below

3
Etienne de Martel On

According to this:

Stack is not unwound: destructors of variables with automatic storage duration are not called.

Your std::ofstream never gets destructed, then, which means its buffer isn't closed, so anything it still contains (and hasn't been flushed to disk) is therefore lost.

So, no, it's not a bug. It's working exactly as designed.