In C, which is the better practice when it comes to freeing memory returned from functions:
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With