Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeing memory returned from C functions

Tags:

c

file

free

In C, which is the better practice when it comes to freeing memory returned from functions:

  • Provide a "destructor" function that encapsulates the call to free().
  • Require users to free() the returned pointer themselves.

For example, to open and close a file we do:

FILE* f = fopen("blah", "w");
fclose(f);

Is this preferable to:

FILE* f = fopen("blah", "w");
fclose(f);
free(f);

Warning: Don't call free() on a FILE pointer. I only use it a hypothetical implementation here.

And what about cases where local variables are pointed to the returned memory? Is free() harmful here? (or perhaps this should never be done)

FILE f = &fopen("blah", "w");
fclose(&f);
like image 905
Kai Avatar asked May 26 '09 16:05

Kai


1 Answers

The best option for allocating and freeing memory is to do it symmetrically. i.e. If the caller allocates memory, let the caller free it. If your API allocs memory (callee), then your API should free it.

Example of caller alloc/free:

int * mymem = (int *)malloc(20 * sizeof(int));
...
a_func_to_call(mymem);
...
free(mymem);

Example of callee alloc/free:

FILE* f = fopen("blah", "w"); // allocs a FILE struct
fclose(f); // The implementation of fclose() will do what's necessary to 
           // free resources and if it chooses to deallocate any memory
           // previously allocated
like image 90
Adam Markowitz Avatar answered Oct 05 '22 11:10

Adam Markowitz