Valgrind Tutorial -Part 4

Invalid Free:Whenever your trying to free a memory location twice , the application crashes.Using valgrind , we can also know whether our code is doing invalid free or not.


int main(void)
{
        int *ptr, i;
        ptr = malloc(10*sizeof(int));
        for(i = 0;i < 10;i++)
                ptr[i] = i;
        free(ptr);
        free(ptr);        /* Error: ptr has already been freed */
        return 0;
}


In the following program we have allocated a pointer and allocated 10 integer variables and in the next step we are initializing each of the variable. Next we will free the heap memory allocated. But in the next step we are trying to free the already freed memory which is wrong. So with valgrind you can check this error also.
compile the application using gcc

  gcc -o app app.c -g
Run the valgrind tool
valgrind --tool=memcheck --leak-check=yes  ./app
O/P:
==31277== Memcheck, a memory error detector
==31277== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==31277== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==31277== Command: ./app
==31277==
==31277== Invalid free() / delete / delete[] / realloc()
==31277==    at 0x402B06C: free (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==31277==    by 0x804846B: main (test4.c:16)
==31277==  Address 0x41fa028 is 0 bytes inside a block of size 40 free'd
==31277==    at 0x402B06C: free (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==31277==    by 0x804845F: main (app.c:15)
==31277==
==31277==
==31277== HEAP SUMMARY:
==31277==     in use at exit: 0 bytes in 0 blocks
==31277==   total heap usage: 1 allocs, 2 frees, 40 bytes allocated
==31277==
==31277== All heap blocks were freed -- no leaks are possible
==31277==
==31277== For counts of detected and suppressed errors, rerun with: -v
==31277== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

PR, PN and PV Variable in Yocto