Sunday 18 December 2016

How to fix double free or corruption error using valgrind

he double free or corruption error will occur when there is a bad memory usage. Bad memory means you are using a location in memory which is not allocated or it is allocated to some other variable.

It can also occur if you try to free a memory other than the allocated memory.

This will generate segmentation fault. The segmentation fault may not occur sometimes because there are only few processes running in the system. The segmentation fault will usually occur with 100% probability in hardware boards but may not occur sometimes when running on the cpu.

The best ways that I suggest to analyse these crashes are the tools - Valgrind and Gdb.

Consider the example as shown 

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

int main()
{
    int *p;
    p = (int *)malloc(1*sizeof(int));
    printf(" first free\n");
    free(p);
    printf(" first free done\n");
    printf(" second free\n");
    free(p);
    printf(" second free done\n");
    return 0;
}

1.compile the code with -g flag 
gcc -g memcheck.c 

2. run the executable generated as 
valgrind --tool=memcheck --leak-check=full ./a.out

3. The result/output will be 

==14861== Memcheck, a memory error detector
==14861== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==14861== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==14861== Command: ./a.out
==14861== 
 first free
 first free done
 second free
==14861== Invalid free() / delete / delete[] / realloc()
==14861==    at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14861==    by 0x400608: main (memcheck.c:12)
==14861==  Address 0x51fc040 is 0 bytes inside a block of size 4 free'd
==14861==    at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==14861==    by 0x4005E8: main (memcheck.c:9)
==14861== 
 second free done
==14861== 
==14861== HEAP SUMMARY:
==14861==     in use at exit: 0 bytes in 0 blocks
==14861==   total heap usage: 1 allocs, 2 frees, 4 bytes allocated
==14861== 
==14861== All heap blocks were freed -- no leaks are possible
==14861== 
==14861== For counts of detected and suppressed errors, rerun with: -v
==14861== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

The result shows that the memory has been freed two times, Hence easy to analyse. 
Use the -g flag during the compilation so that the line number of the double free is also shown.

1 comment: