Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What REALLY happens when you don't free after malloc?

Tags:

c

malloc

free

We are all taught that you MUST free every pointer that is allocated. I'm a bit curious, though, about the real cost of not freeing memory. In some obvious cases, like when malloc() is called inside a loop or part of a thread execution, it's very important to free so there are no memory leaks. But consider the following two examples:

First, if I have code that's something like this:

int main() {     char *a = malloc(1024);     /* Do some arbitrary stuff with 'a' (no alloc functions) */     return 0; } 

What's the real result here? My thinking is that the process dies and then the heap space is gone anyway so there's no harm in missing the call to free (however, I do recognize the importance of having it anyway for closure, maintainability, and good practice). Am I right in this thinking?

Second, let's say I have a program that acts a bit like a shell. Users can declare variables like aaa = 123 and those are stored in some dynamic data structure for later use. Clearly, it seems obvious that you'd use some solution that will calls some *alloc function (hashmap, linked list, something like that). For this kind of program, it doesn't make sense to ever free after calling malloc because these variables must be present at all times during the program's execution and there's no good way (that I can see) to implement this with statically allocated space. Is it bad design to have a bunch of memory that's allocated but only freed as part of the process ending? If so, what's the alternative?

like image 805
Scott Avatar asked Mar 17 '09 15:03

Scott


People also ask

Do I need to free memory after malloc?

The malloc function will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory. When the amount of memory is not needed anymore, you must return it to the operating system by calling the function free.

What happens if you don't deallocate memory?

If you don't deallocate this memory, you have a memory leak (memory that was allocated, but never deallocated, and therefore can't be used by your program in the future). Memory allocation/deallocation rule: IF YOU ALLOCATE IT (use a new), YOU MUST DEALLOCATE IT (delete it)! See the destructor of Array for an example.

What happens when we don't free the dynamically allocated memory?

If dynamically allocated memory is not freed, it results in a memory leak and system will run out of memory. This can lead to program crashing.

What happens when you free malloc?

The free function deallocates the block of memory pointed at by ptr . Occasionally, free can actually return memory to the operating system and make the process smaller. Usually, all it can do is allow a later call to malloc to reuse the space.


2 Answers

Just about every modern operating system will recover all the allocated memory space after a program exits. The only exception I can think of might be something like Palm OS where the program's static storage and runtime memory are pretty much the same thing, so not freeing might cause the program to take up more storage. (I'm only speculating here.)

So generally, there's no harm in it, except the runtime cost of having more storage than you need. Certainly in the example you give, you want to keep the memory for a variable that might be used until it's cleared.

However, it's considered good style to free memory as soon as you don't need it any more, and to free anything you still have around on program exit. It's more of an exercise in knowing what memory you're using, and thinking about whether you still need it. If you don't keep track, you might have memory leaks.

On the other hand, the similar admonition to close your files on exit has a much more concrete result - if you don't, the data you wrote to them might not get flushed, or if they're a temp file, they might not get deleted when you're done. Also, database handles should have their transactions committed and then closed when you're done with them. Similarly, if you're using an object oriented language like C++ or Objective C, not freeing an object when you're done with it will mean the destructor will never get called, and any resources the class is responsible might not get cleaned up.

like image 77
Paul Tomblin Avatar answered Sep 16 '22 14:09

Paul Tomblin


Yes you are right, your example doesn't do any harm (at least not on most modern operating systems). All the memory allocated by your process will be recovered by the operating system once the process exits.

Source: Allocation and GC Myths (PostScript alert!)

Allocation Myth 4: Non-garbage-collected programs should always deallocate all memory they allocate.

The Truth: Omitted deallocations in frequently executed code cause growing leaks. They are rarely acceptable. but Programs that retain most allocated memory until program exit often perform better without any intervening deallocation. Malloc is much easier to implement if there is no free.

In most cases, deallocating memory just before program exit is pointless. The OS will reclaim it anyway. Free will touch and page in the dead objects; the OS won't.

Consequence: Be careful with "leak detectors" that count allocations. Some "leaks" are good!

That said, you should really try to avoid all memory leaks!

Second question: your design is ok. If you need to store something until your application exits then its ok to do this with dynamic memory allocation. If you don't know the required size upfront, you can't use statically allocated memory.

like image 31
compie Avatar answered Sep 20 '22 14:09

compie