Valgrind Tutorial - Part 1

Today we will be starting a series on Valgrind.We will writing various programs and use valgrind to detect the possible errors that can occur.

About Valgrind:
1. Debugging Tool
2.It is a wrapper around various tools for debugging and profiling.Best tool out of these is MemCheck that is used to find out memory leaks etc.


In order to use valgrind you have to include debugging information that is you should compile the application with -g option if you are using gcc .

We will use the  Memcheck tool to find out memory leak

C-Program


int main(void)
{
  char *ptr;

  /**Here we are allocating 19 bytes of memory using malloc **/
  ptr = (char *)malloc(19);

  /**Here we are again allocating 12 bytes of memory using 
   *malloc to the same pointer **/
  ptr = (char *) malloc(12);
  free(ptr);

  /**Allocating 16 bytes using malloc**/
  ptr = (char *) malloc(16);

  return 0;
}
  
Now when we compile the application using gcc

  gcc -o app app.c -g

It will generate the binary app with the debugging information included so that line numbers are displayed when there are errors.

Now if we want debug using valgrind type the following command in the terminal

valgrind --tool=memcheck --leak-check=yes  ./app

Once you run this,it displays a list of errors

==8184== Memcheck, a memory error detector
==8184== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==8184== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==8184== Command: ./app
==8184== 
==8184== 
==8184== HEAP SUMMARY:
==8184==     in use at exit: 35 bytes in 2 blocks
==8184==   total heap usage: 3 allocs, 1 frees, 47 bytes allocated
==8184== 
==8184== 16 bytes in 1 blocks are definitely lost in loss record 1 of 2
==8184==    at 0x402BE68: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==8184==    by 0x8048454: main (app.c:27)
==8184== 
==8184== 19 bytes in 1 blocks are definitely lost in loss record 2 of 2
==8184==    at 0x402BE68: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==8184==    by 0x8048428: main (app.c:20)
==8184== 
==8184== LEAK SUMMARY:
==8184==    definitely lost: 35 bytes in 2 blocks
==8184==    indirectly lost: 0 bytes in 0 blocks
==8184==      possibly lost: 0 bytes in 0 blocks
==8184==    still reachable: 0 bytes in 0 blocks
==8184==         suppressed: 0 bytes in 0 blocks
==8184== 
==8184== For counts of detected and suppressed errors, rerun with: -v
==8184== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)

Explanation:
8184 is the process id,

Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

PR, PN and PV Variable in Yocto