K
Keith Thompson
Michael Mair said:As long as your operating system or implementation does not
_guarantee_ you that allocated storage is taken care of as if
you had free()d it explicitly, I'd rather explicitly free()
the storage.
Agreed, for several reasons (which you've already covered): the
program might some day become a function within a larger program, and
free() can sometimes show allocation errors that you would have
missed).
The common wisdom seems to be that memory allocated by malloc() will
*usually* be automatically deallocated by the operating system when
the program terminates (and will almost certainly be deallocated on
any modern OS), but that it's not guaranteed. I agree that it's not
guaranteed, but on the other hand, it's also not guaranteed that
calling free() will actually do any good.
More concretely:
#include <stdlib.h>
int main(void)
{
void *ptr = malloc(1000);
if (ptr == NULL) exit(EXIT_FAILURE);
#ifdef CALL_FREE
free(ptr);
#endif
exit(EXIT_SUCCESS);
}
On most systems, I'd expect the program to behave the same way whether
CALL_FREE is defined or not, i.e., the allocated memory will be
reclaimed when the program terminates. But if this program causes a
system-level memory leak without CALL_FREE, is there any reason to
assume defining CALL_FREE will plug the leak? Calling free() merely
causes the allocated space to be "made available for further
allocation", presumably within the program itself. It doesn't
necessarily return the space to the operating system *or* cause it to
be returned to the OS when the program terminates.
Are there any real-world systems where the above program actually
causes a memory leak with CALL_FREE not defined? If so, does defining
CALL_FREE actually plug the leak on all such systems?
None of this affects the principle that you should always free() all
the memory you malloc().