47

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);
}
10
  • 4
    I see no reason. OS will do that for you. Commented Apr 12, 2016 at 21:09
  • 12
    But it is a good habit to clean after yourself.
    – Eugene Sh.
    Commented Apr 12, 2016 at 21:10
  • 4
    While it is true that the OS will do it for you, what happens when OP adds a new function to do some processing and then another and then another? Or worse, when the new guy (gal) comes on and starts modifying? My advice, free all allocated memory. Oh, and do not cast the results of your allocations. Ever.
    – KevinDTimm
    Commented Apr 12, 2016 at 21:11
  • 1
    Possible duplicate of Is leaked memory freed up when the program exits? Commented Apr 12, 2016 at 21:34
  • 1
    One advantage of not freeing is that if your program has a large number of allocations, then freeing on exit will slow down your application's exit sequence.
    – M.M
    Commented Apr 12, 2016 at 21:53

5 Answers 5

59

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.

5
  • 8
    Well said! Restating a comment I made below: if you're a newbie, in general, make "free it manually" the habitual instinct (less dangerous habit), and make "leave it to the OS" be a conscious, informed, case-by-case decision. The decision-making process for that will become instinct over time. Otherwise, you'll habitually forget to free your mallocs and clean up your dangling pointers, and you're subsequently signing up for surprise UBs the next time you change your code in such a way that failing to free the memory now matters. Commented Apr 12, 2016 at 21:40
  • 1
    @JasonMc92 while that sounds nice, it is building extra unreliablity into today's code. Explicitly freeing memory at app termination is not free, not safe and not always possible. It's usually unnecessary extra code that needs to be tested and debugged, over, and over again, on all OS versions. It's uni cargo-cult mantras like 'you must always explicitly free before terminating' that result in the many apps we have both used that will not shut down cleanly and quickly:( Commented Apr 13, 2016 at 12:00
  • 3
    As I said on the other (longer) comment chain: the link in the answer backs up my point. By and large, freeing manually (overall, not just at program end) is usually an issue of stability (short- and long-term), while not freeing manually is usually an issue of performance, and we all know the adage: "Premature optimization is the root of all evil." (-Donald Knuth). Free by habit, decide not to by choice, not to ensure OS gets the memory back, but to prevent errors when we refactor code later. Beyond that, we have a "holy war" and had probably best agree to disagree. Commented Apr 13, 2016 at 14:50
  • 1
    I found running under no OS being the ultimate no memory leaks. When your exit chainloads the next program it comes up just as yours did and sees all the memory in the computer as randomly initialized free memory.
    – Joshua
    Commented Aug 16, 2018 at 22:06
  • 1
    You could argue that if it's a lot of work to free, then the program is poorly designed.
    – klutt
    Commented Aug 4, 2020 at 7:52
18

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.

0
13

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.

6
  • 5
    Which systems cannot free memory after program termination?
    – fuz
    Commented Apr 12, 2016 at 21:22
  • 1
    Have a look in the comments here... stackoverflow.com/questions/2975831/… and here. stackoverflow.com/questions/6727383/…
    – Harry
    Commented Apr 12, 2016 at 21:26
  • 5
    The way to handle temp files is to delete them on runup, not on shutdown. Power can fail at any time, and apps that rely absoultely on a shutdown procedure will be in trouble. Commented Apr 12, 2016 at 21:28
  • 1
    @Harry If you are programming for such a system, you know this and don't ask this kind of question on Stack Overflow.
    – fuz
    Commented Apr 12, 2016 at 21:30
  • 2
    @MartinJames do both? Leave no mess behind, boyscott principle and all
    – Sled
    Commented Jan 30, 2019 at 22:38
13

You don't need to free memory before program termination. Terminating the program in any way causes all memory to be deallocated automatically.

17
  • 7
    In a hosted environment with proper process isolation, and ignoring things like shared memory...
    – user3185968
    Commented Apr 12, 2016 at 21:13
  • 3
    I want to down vote this answer as these are the kinds of things that eventually bite us. I didn't, but I want to.
    – KevinDTimm
    Commented Apr 12, 2016 at 21:14
  • 3
    @JasonMc92 I disagree. On error exit, it's often very hard or impossible to correctly clean up all the memory as data structures may be corrupted. Attempting to clean things up is a futile endeavour.
    – fuz
    Commented Apr 12, 2016 at 21:18
  • 4
    I think what I'm saying is this: we need to default to manual clean up, and make a conscious decision to leave it to the OS when appropriate. If we default to "let the OS to it" and have to make a conscious decision to clean up ourselves, we are more likely to "forget" things that lead to dangling pointers and the like (especially during code rewriting), and thereby yield UBs. The decision to not clean up manually needs to be an educated intentional choice, as I'm sure it is for ya'll by habit. Less experienced coders need to form that habit. Commented Apr 12, 2016 at 21:34
  • 3
    The way to form that habit, of course, is to habitually plan for manual cleanup when possible, and when they realize it will be difficult/impractical/dangerous, making the conscious decision of "I had better leave this to the operating system to clean up." With the opposite habit, many a newbie coder will decide "I don't need to free my malloc. The OS will do it!" and fail to notice that they're asking for a swarm of nasal demons five lines later. Commented Apr 12, 2016 at 21:38
0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.