19

Assume I have the following program:

#include <stdio.h>

int main () {
    FILE * pFile;
    pFile = fopen ("myfile.txt","r");

    fclose (pFile);
    //This never happens: free(pFile)
    return 0;
}

I have never seen a program which does free(pFile) after closing the file handle. Why is that?

I know that since fclose() doesn't receive a pointer to pFile, then it doesn't actually free the pointer's memory. I was under the impression that pointers should always have their memory freed if they are pointing to dynamically allocated memory. Why doesn't anyone free() the file pointer?

Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195
  • "Why doesn't anyone `free()` the file pointer?" - because it would be plain wrong. – The Paramagnetic Croissant Nov 16 '14 at 06:34
  • `free()` doesn't receive a pointer to its argument either. – Keith Thompson Nov 16 '14 at 06:34
  • first, you do NOT want to be calling free on the file descriptor table (where the FILE * points is to some entry in that table) second, you only call free() on a pointer that was set by one of the malloc() family of functions (certain functions, like dup() use malloc in the background, so the resulting pointer needs to be free'd) – user3629249 Nov 17 '14 at 01:41
  • When you pass pFile to fclose, you're passing a FILE*. So fclose certainly could call free on it, and it would have the same effect as if you did this yourself. However what actually happens is more complicated. – John Leuenhagen Nov 12 '19 at 04:51

4 Answers4

32

free is called in response to malloc to return allocated memory. fopen likely indeed does do some mallocing, but the act of closing the handle (fclose) is, by design, going to clean up everything fopen did. The contract you have with fopen is that closing the handle will free all outstanding resources.

The general rule of thumb is for every alloc have a free. If you call a function which does an alloc, it's description should warn you of what the caller is responsible for freeing.

Long story short, fclose will clean up any resources created by fopen.

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
Ben
  • 2,867
  • 2
  • 22
  • 32
5

Memory allocation of the fopen function is implementation dependent (per CRT). You can be sure that fclose is always implemented to free all the memory that fopen allocated.

Tzach
  • 12,889
  • 11
  • 68
  • 115
1

fclose() will release the related resources. However, when you finish executing the command fclose(fp); , the fp is still not NULL. Hence, you need to assign NULL to it explicitly.

Jie Yin
  • 560
  • 5
  • 9
0

When closing the file more than once, fclose returns 0 the first time, but -1 thereafter.

Therefore, it probably takes care of it in a smart way.

At least this is the case in Windows, please correct me if I'm wrong.

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40