Memory debugger is a programming tool used for dedtecting memory leak and bufferoverflow. In open source linux environment, valgrind and electricfence are such tools which are widely used by developers to diagnose memory leak/corruption and bufferoverflow like bugs.

REQUIREMENT
Before using valgrind tool your program needs to be compiled with -g option to gcc compiler.
Ex. gcc -g yourprogram.c -o yourprogram

HOW TO INSTALL VALGRIND

For Debian/Ubuntu based distribution run
alen@Alen-Vostro-1550:~$ sudo apt-get install valgrind

For CentOS / Redhat / RHEL Linux:
# yum install valgrind

HOW TO USE VALGRIND

/* file name test.c */

/* gcc -g test.c -o test */

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

int main()
{
char *p = (char*)malloc(1024);
char *q = (char*)malloc(1024);

p = q;
free(p);
free(q);

return 0;
}

When we compile and run the above program we will get error

*** Error in `./a.out’: double free or corruption (top): 0x0000000002589420 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x80996)[0x7ff4862da996]
./a.out[0x4005c1]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf5)[0x7ff48627bde5]
./a.out[0x4004b9]

Now let us run test program with valgrind tool at command prompt: 

alen@Alen-Vostro-1550:~$ valgrind ./test
==3836== Memcheck, a memory error detector
==3836== Copyright (C) 2002-2012, and GNU GPL’d, by Julian Seward et al.
==3836== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==3836== Command: ./test
==3836==
==3836== Invalid free() / delete / delete[] / realloc()
==3836== at 0x4C2B60C: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3836== by 0x4005C0: main (test.c:11)
==3836== Address 0x51fc480 is 0 bytes inside a block of size 1,024 free’d
==3836== at 0x4C2B60C: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==3836== by 0x4005B4: main (test.c:10)
==3836==
==3836==
==3836== HEAP SUMMARY:
==3836== in use at exit: 1,024 bytes in 1 blocks
==3836== total heap usage: 2 allocs, 2 frees, 2,048 bytes allocated
==3836==
==3836== LEAK SUMMARY:
==3836== definitely lost: 1,024 bytes in 1 blocks
==3836== indirectly lost: 0 bytes in 0 blocks
==3836== possibly lost: 0 bytes in 0 blocks
==3836== still reachable: 0 bytes in 0 blocks
==3836== suppressed: 0 bytes in 0 blocks
==3836== Rerun with –leak-check=full to see details of leaked memory
==3836==
==3836== For counts of detected and suppressed errors, rerun with: -v
==3836== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)

From the leak summary valgrind reports that there is 1024 bytes of memory leak in the sample program.

References:
See valgrind project web site and the valgrind man page for more information:



Related Contents to follow