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?
The other answers tell you the two important things:
free()
it.However, it's important to say why it's good practice to free()
everything you've malloced. In my view:
O.S. will reclaim the memory not free'd up.
But is a good practice to free all memory allocated by malloc
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With