Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fclose() then free()?

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?

like image 581
Oliver Spryn Avatar asked Nov 16 '14 06:11

Oliver Spryn


2 Answers

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.

like image 76
Ben Avatar answered Sep 21 '22 20:09

Ben


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.

like image 39
Tzach Avatar answered Sep 23 '22 20:09

Tzach