Valgrind Tutorial - Part 2
By using valgrind we can also find out whether we are performing read/write operation on an array beyond its limit(size)
Take a look at this sample code
Take a look at this sample code
int main(void) { int i; int *a = malloc(sizeof(int) * 12); if (!a) return -1; /*malloc operation has failed*/ for (i = 0; i < 15; i++){ a[i] = i; } free(a); return 0; }You can see in the following code that iam allocating a integer array of size 12 by using malloc but i am trying to access beyond the size of array that is array[12],array[13] and array[14] which is wrong By using valgrind memcheck tool you can find out the error So first compile the code by passing -g to gcc to include debugging operation
gcc -o app app.c -g
Now run the valgrind tool using the following command
valgrind --tool=memcheck --leak-check=yes ./app
==29768== Memcheck, a memory error detector
==29768== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==29768== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==29768== Command: ./app
==29768==
==29768== Invalid write of size 4
==29768== at 0x8048454: main (app.c:18)
==29768== Address 0x41fa050 is 0 bytes after a block of size 40 alloc'd
==29768== at 0x402BE68: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==29768== by 0x8048428: main (app.c:13)
==29768==
==29768==
==29768== HEAP SUMMARY:
==29768== in use at exit: 0 bytes in 0 blocks
==29768== total heap usage: 1 allocs, 1 frees, 40 bytes allocated
==29768==
==29768== All heap blocks were freed -- no leaks are possible
==29768==
==29768== For counts of detected and suppressed errors, rerun with: -v
==29768== ERROR SUMMARY: 5 errors from 1 contexts (suppressed: 0 from 0)
Comments
Post a Comment