Should I free all my mallocated memory when I am exiting program in the due of error?
something = (char**) malloc (x * sizeof(char*));
for (i = 0; i < x; i++)
something[i] = (char*) malloc (y + 1);
...
if (anything == NULL) {
printf("Your input is wrong!");
// should I free memory of every mallocated entity now?
exit(1);
}
else {
// work with mallocated entities
...
free(something); // it must be here
system("pause);
}
This is actually a really hard, imponderable question.
Pro (in favor of freeing everything before exit):
Con (just exit, don't worry about freeing everything):
In the end, you will have to decide which of these pros and cons matters most for you. Different programmers on different projects under different circumstances will reach different conclusions; there is no one-size-fits-all answer here.
See also question 7.24 in the C FAQ list.
I had completely opposite scenario: segfaulting destructors of static objects from third-party library. Just because of explicitly freeing memory pools before exit. I believe, it is better to be reasonable and to concentrate on program structure.
You don't need to free memory before program termination. Terminating the program in any way causes all memory to be deallocated automatically.
It depends on the OS. Best practice I'd say you should explicitly free it. It also makes using tools like valgrind a PITA if you have memory not freed all over the place and I cannot tell what's good and bad etc.
If on an OS that explicitly frees memory you still have the problem of other resources. As your app starts to grow and pull in third party libraries you can get resource leaks. Imagine I've written a library that asks that you call close on a handler. This handler happens to be backed by temporary files that doesn't get deleted unless you call close. Or I've detached processes that are running in the background that I'm managing using signals or some other resource that you're unaware of.
You should always free allocated memory before you exit. As already mentioned in other answers, this will minimize warnings from static- or dynamic analysis tools etc.
But the real reason why you should always do this, is because freeing often exposes dormant run-time bugs in your application.
If you have a bug somewhere that causes memory corruption or changes pointer addresses, that bug may stay silent and dormant. Until you change something completely unrelated to the bug and thereby shuffle around the memory layout. Then suddenly you get a crash and you'll have no idea why, because the bug isn't even located in the code you just added.
By freeing the memory, you provoke such bugs to surface. Because if there is anything wrong with the heap or with the pointers pointing at the heap, then you will often get a crash at the point where you call
free()
. Which means that you have a severe bug somewhere, that you need to find before shipping the program.