A memory bug detector

This interesting tool valgrind is a debug tool and can been used to find memory bug, include memory leak. There is a rpm in Fedora Core 3 CD. You can get it from CD or download the source code from their website. Moreover, this tool is a Free Software, and is freely available under the GNU General Public License. You can use it to debug Linux programs and it’s very easy to use.


Assume that you have already installed the tool on your system, and now let’s take a simple example to illustrate its usage.
1. Compile the following program mem.c to binary file mem with debug information, e.g. use gcc‘s “-g” option.

#include
#define STR    "Hello"
int main(int argc,char* argv[])
{
char *str_list[10];
int i=0;
while( i<10 )
{
str_list[i]=(char*)malloc(strlen(STR));
strcpy(str_list[i],STR);
i++;
}
i=0;
while( i<9 )
{
free(str_list[i]);
i++;
}
return(0);
}

2. use the default command:

valgrind  mem

3. then, you will get a report like below.


==15605== Memcheck, a memory error detector.
==15605== Copyright (C) 2002-2005, and GNU GPL'd, by Julian Seward et al.
==15605== Using LibVEX rev 1367, a library for dynamic binary translation.
==15605== Copyright (C) 2004-2005, and GNU GPL'd, by OpenWorks LLP.
==15605== Using valgrind-3.0.1, a dynamic binary instrumentation framework.
==15605== Copyright (C) 2000-2005, and GNU GPL'd, by Julian Seward et al.
==15605== For more details, rerun with: -v
==15605==
==15605== Invalid write of size 1
==15605==    at 0x1B901374: strcpy (mac_replace_strmem.c:269)
==15605==    by 0x8048421: main (mem.c:14)
==15605==  Address 0x1BA4E029 is 0 bytes after a block of size 1 alloc'd
==15605==    at 0x1B8FF88D: malloc (vg_replace_malloc.c:149)
==15605==    by 0x8048406: main (mem.c:13)
==15605==
==15605== ERROR SUMMARY: 10 errors from 1 contexts (suppressed: 20 from 3)
==15605== malloc/free: in use at exit: 1 bytes in 1 blocks.
==15605== malloc/free: 10 allocs, 9 frees, 10 bytes allocated.
==15605== For counts of detected errors, rerun with: -v
==15605== searching for pointers to 1 not-freed blocks.
==15605== checked 65536 bytes.
==15605==
==15605== LEAK SUMMARY:
==15605==    definitely lost: 1 bytes in 1 blocks.
==15605==      possibly lost: 0 bytes in 0 blocks.
==15605==    still reachable: 0 bytes in 0 blocks.
==15605==         suppressed: 0 bytes in 0 blocks.
==15605== Use --leak-check=full to see details of leaked memory.

We can get some info from the report. First, this report tell us the program write 1 byte to an invalid address at mem.c:14 using strcpy. Second, we allocate 10 block memory, but only free 9 blocks. Those bugs are what we have done in mem.c on purpose. However this is just a simple report and for more infomation about this tool, you can check out the offical website.

Leave a Reply

Your email address will not be published. Required fields are marked *