Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); } 
like image 921
Lucfia Avatar asked Apr 12 '16 21:04

Lucfia


People also ask

Does exit free all memory?

Yes, all memory is returned.

What happens if I dont free allocated memory?

In these cases, even small chunks of storage add up and create a problem. Thus our usable space decreases. This is also called “memory leak”. It may also happen that our system goes out of memory if the de-allocation of memory does not take place at the right time.

Why do you need to free memory?

However on long running programs, failing to free memory means you will be consuming a finite resource without replenishing it. Eventually it will run out and your program will rudely crash. This is why you must free memory.

What happens when you free memory?

free() just declares, to the language implementation or operating system, that the memory is no longer required. When it is written over is not defined behavior.


1 Answers

This is actually a really hard, imponderable question.

Pro (in favor of freeing everything before exit):

  • no bugs or memory leaks later if code is rearranged
  • no false positives from valgrind or memory leak checker
  • no memory leaks if you're running under a buggy OS, or no OS at all

Con (just exit, don't worry about freeing everything):

  • freeing everything can be a lot of work
  • freeing everything can introduce bugs and crashes
  • your OS really, really ought to reclaim all resources for you when you exit

And, one more point (not sure if it's a pro or a con): on the majority of systems, calling free does not return memory to the Operating System (only exiting does that).

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 this previous Stack Overflow question. See also question 7.24 in the C FAQ list.

like image 169
Steve Summit Avatar answered Sep 21 '22 13:09

Steve Summit