Search code examples
filefopenexit

What happens if you exit a program without doing fclose()?


Question:

What happens if I exit program without closing files?

Are there some bad things happening (e.g. some OS level file descriptor array is not freed up..?)

And to the answer the same in both cases

  • programmed exiting
  • unexpected crash

Code examples:

With programmed exiting I mean something like this:

int main(){
    fopen("foo.txt","r");
    exit(1);
}

With unexpected crash I mean something like this:

int main(){
    int * ptr=NULL;
    fopen("foo.txt","r");
    ptr[0]=0;  // causes segmentation fault to occur
}

P.S.

If the answer is programming language dependent then I would like to know about C and C++.

If the answer is OS dependent then I am interested in Linux and Windows behaviour.


Solution

  • It depends on how you exit. Under controlled circumstances (via exit() or a return from main()), the data in the (output) buffers will be flushed and the files closed in an orderly manner. Other resources that the process had will also be released.

    If your program crashes out of control, or if it calls one of the alternative _exit() or _Exit() functions, then the system will still clean up (close) open file descriptors and release other resources, but the buffers won't be flushed, etc.