cmallocfreedynamic-allocation

Should I free memory before exit?


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

Solution

  • 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.