16

Say I have the following program

#include <stdio.h>
#include <stdlib.h>

int main(void) 
{
    int * i;

    if ((i = malloc(sizeof(int) * 100)) == NULL) {
        printf("EROOR: unable to allocate memory \n");
        return -1;
    }

    /* memory is allocated successfully */

    /* memory is not free'ed but program terminates */
    // free(i);

    return 0;
}

The above program calls malloc to allocate some memory and does not call free to de-allocate it. And the program terminates without de-allocating the memory.

Valgrind clearly detects a memory leak.

<snap>
==14209== HEAP SUMMARY:
==14209==     in use at exit: 400 bytes in 1 blocks
==14209==   total heap usage: 1 allocs, 0 frees, 400 bytes allocated
==14209== 
<sanp>
==14209== LEAK SUMMARY:
==14209==    definitely lost: 400 bytes in 1 blocks
==14209==    indirectly lost: 0 bytes in 0 blocks
==14209==      possibly lost: 0 bytes in 0 blocks
==14209==    still reachable: 0 bytes in 0 blocks
==14209==         suppressed: 0 bytes in 0 blocks
==14209== 
==14209== For counts of detected and suppressed errors, rerun with: -v
==14209== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

Question:

When the program terminates, what happens to the memory that was allocated but not free'd?

Update: Consider that this code is being executed on different operation system - say windows, linux, solarix, macos, etc. Is there any difference in the behavior of this code during its termination?

Destructor
  • 14,123
  • 11
  • 61
  • 126
Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98
  • 3
    In most modern operating systems, all the programs resources are freed or closed. – Some programmer dude Apr 19 '12 at 07:46
  • Can I ask you what triggered this question? Rather than worry about what happens if you don't free, why don't you just free? Then you can stop worrying; valgrind is happen, everybody's happy. Problem solved. – Mr Lister Apr 19 '12 at 07:49
  • Duplicate of http://stackoverflow.com/questions/654754/what-really-happens-when-you-dont-free-after-malloc – alexis Apr 19 '12 at 07:54
  • I think it's a rather valid and interesting question in fact : what does the O/S do with this allocated memory (and other resources ?) when a process exits? Gives an insight of how the underlying system works, allocates pages from the virtual memory system. Lots of things to learn there (process & memory management, virtual memory in a processor). Even though I know the answer, it makes me wonder "But, how does it work EXACTLY ?". You learn so much by trying to do things that you're not supposed to do, instead of just not doing them and not knowing what would be the consequences. :o) – huelbois Apr 19 '12 at 07:56
  • @MrLister We don't skip `free` intentionally. Most often we work on huge code base where `malloc` is done by one module and `free` is done is another module, etc. And these programs runs on windows, solaris, linux, mac os, etc. So I was curious how the un-freed case is handled. – Sangeeth Saravanaraj Apr 19 '12 at 07:59
  • @huelbois True, you can learn a lot by trying out things that you're not supposed to do. As long as you _never, ever use those things in production!_ – Mr Lister Apr 19 '12 at 08:02
  • I see horrifying things every day in production!Some problems only occur in production, when the traffic is high and resources are limited. Of course I 100% agree with you,I only wanted to pinpoint that instead of not doing things "because every body tells you it's bad", I find it better to really find out why it's bad, have a real understanding of the consequences.And one of the best ways to do it, of course, is to try it yourself until you face the announced consequences - as long as no harm is done. Then you will not only know it's bad, but you also learn how it goes bad. Learn learn learn! – huelbois Apr 19 '12 at 08:17

5 Answers5

14

The other answers tell you the two important things:

  1. Yes, the memory is reclaimed by the OS, so you don't technically need to free() it.
  2. It's good practice to free everything you malloced anyway.

However, it's important to say why it's good practice to free() everything you've malloced. In my view:

  1. Habit: If you get in the habit of freeing whenever you've malloced, you won't accidentally forget when a memory segment isn't around for the lifetime of the program.
  2. Maintainability: If someone comes along to refactor your program so that a segment of memory is no longer around for the lifetime of the program, the presence of cleanup code in the original will mean that it's very likely that the refactored version also includes the cleanup code. For me, this is the most important reason.
  3. Debugging: If we expect that all memory is cleaned up correctly, then spotting memory that's actually leaking is much easier.
Timothy Jones
  • 21,495
  • 6
  • 60
  • 90
7

O.S. will reclaim the memory not free'd up.

But is a good practice to free all memory allocated by malloc

DonCallisto
  • 29,419
  • 9
  • 72
  • 100
  • that's open to debate: http://stackoverflow.com/a/6347182/48015 ; disabling explicit deallocation before program termination for production builds is probably a good idea... – Christoph Apr 19 '12 at 07:57
4

The memory is reclaimed by the Operating system once your program exits.
The OS doesn't understand that your program leaked memory, it simply allocates memory to the program for running and once the program exits it reclaims that memory.

However, other resources like file descriptors may/may not be recalimed by the OS causing a resource leak.

So it is a good practice that a program should cleanup all the resource it utilized before exiting.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

When a process allocates memory dynamically, it borrows block(s) of memory from OS. When a process doesn't need allocated memory it free(s). Then OS adds those blocks to its free list. The same happens when a process terminates. All the blocks used by the process is reclaimed by the OS.

Read memory-management for more info.

tuxuday
  • 2,977
  • 17
  • 18
0

More importantly, FREE ensures the sanity of the memory/buffers allocated by you, and hence forth exsisting a good checkpoint for curbing/catching up heap corruption.