In C, which is best practice when it comes to freeing the memory returned from functions:
- Provide a destructor function that encapsulates the call in free ().
- Require users of a free () returned pointer.
For example, to open and close a file, we do:
FILE* f = fopen("blah", "w");
fclose(f);
This is preferable:
FILE* f = fopen("blah", "w");
fclose(f);
free(f);
Warning: Do not call free () in the FILE pointer. I use it only in a hypothetical implementation.
What about cases where local variables are referenced in returned memory? Is free () harmful here? (or perhaps this should never be done)
FILE f = &fopen("blah", "w");
fclose(&f);
source
share