4. A Closer View

4.2. Usage

4.2.2. How to Identify the Error from the Error Report

Consider the output of Valgrind for some test program:


   ==1353== Invalid read of size 4
   ==1353==    at 0x80484F6: print (valg_eg.c:7)
   ==1353==    by 0x8048561: main (valg_eg.c:16)
   ==1353==    by 0x4026D177: __libc_start_main
(../sysdeps/generic/libc-start.c   :129)
   ==1353==    by 0x80483F1: free@@GLIBC_2.0 (in /home/deepu/valg/a.out)
   ==1353==    Address 0x40C9104C is 0 bytes after a block of size 40
alloc'd
   ==1353==    at 0x40046824: malloc (vg_clientfuncs.c:100)
   ==1353==    by 0x8048524: main (valg_eg.c:12)
   ==1353==    by 0x4026D177: __libc_start_main
(../sysdeps/generic/libc-start.c   :129)
   ==1353==    by 0x80483F1: free@@GLIBC_2.0 (in /home/deepu/valg/a.out)

Here, 1353 is the process ID. This part of the error report says that a read error has occurred at line number 7, in the function print. The function print is called by function main, and both are in the file valg_eg.c. The function main is called by the function __libc_start_main at line number 129, in ../sysdeps/generic/libc-start.c. The function __libc_start_main is called by free@@GLIBC_2.0 in the file /home/deepu/valg/a.out. Similarly details of calling malloc are also given.

4.2.3. Types of Errors with Examples

Valgrind can only really detect two types of errors: use of illegal address and use of undefined values. Nevertheless, this is enough to discover all sorts of memory management problems in a program. Some common errors are given below.

4.2.3.4. Mismatched Use of Functions

In C++ you can allocate and free memory using more than one function, but the following rules must be followed:

Sample program:


#include <stdlib.h>
int main()
{
        int *p, i;
        p = ( int* ) malloc(10*sizeof(int));
        for(i = 0;i < 10;i++)
                p[i] = i;
        delete(p);                /* Error: function mismatch */
        return 0;
}

Output by valgrind is:


             ==1066== ERROR SUMMARY: 1 errors from 1 contexts (suppressed:
0 from 0)
             ==1066== malloc/free: in use at exit: 0 bytes in 0 blocks.
             ==1066== malloc/free: 1 allocs, 1 frees, 40 bytes allocated.
             ==1066== For a detailed leak analysis,  rerun with:
--leak-check=yes
             ==1066== For counts of detected errors, rerun with: -v

>From the above "ERROR SUMMARY" it is clear that there is 0 bytes in 0 blocks in use at exit, which means that the malloc'd have been freed by delete. Therefore this is not a problem in Linux, but this program may crash on some other platform.

Copyright © 2010-2024 Platon Technologies, s.r.o.           Home | Man pages | tLDP | Documents | Utilities | About
Design by styleshout