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);