Tuesday, February 14, 2012

What is memory leak?


Memory leak: As per Wikipedia memory leak is, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it back to the operating system.

In C language memory leak occurs in dynamic allocation only. Generally there are two possibilities to occur.

1. Allocating the memory using malloc() or calloc() and not freeing that allocated memory using free.

2. free ing the memory without allocation.


One basic rule for checking memory leak is that no. of malloc() functions shoule be equal to the no.of free() functions in the application. There are many tools to detect the memory leaks. In that wellknown tool is valgrind. In all unix machines we can find this tool. I am giving below sample result of a valgrind for the samle code.

main()
{
char *ptr = (char *)malloc(10 * sizeof(char));
//free(ptr); // memory leak , uncomment for no memory leak
}

Valgrind result for the above code:

Unix:~/practice 1801> valgrind a.out

==29043== Memcheck, a memory error detector
==29043== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==29043== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==29043== Command: a.out
==29043==
==29043==
==29043== HEAP SUMMARY:
==29043== in use at exit: 10 bytes in 1 blocks
==29043== total heap usage: 1 allocs, 0 frees, 10 bytes allocated
==29043==
==29043== LEAK SUMMARY:
==29043== definitely lost: 10 bytes in 1 blocks
==29043== indirectly lost: 0 bytes in 0 blocks
==29043== possibly lost: 0 bytes in 0 blocks
==29043== still reachable: 0 bytes in 0 blocks
==29043== suppressed: 0 bytes in 0 blocks
==29043== Rerun with --leak-check=full to see details of leaked memory
==29043==
==29043== For counts of detected and suppressed errors, rerun with: -v
==29043== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
Unix:~/practice 1802>


In the above result, red colored data clearly showing the leakage details. LEAK SUMMARY will be displayed only if any leak occurs in the application/program. And it will give the details about all lost data, In our example it is 10 bytes lost as we are not free'd the allocated data.


No comments:

Popular Posts