Valgrind Tutorial - Part 3

Valgrind also throws an error whenever we are trying to read a uninitialized memory, for example take a look for the following C code


int main(void){
  int i;
  int arr[10];
  for (i = 0; i < 9; i++)
    arr[i] = i;
    
  for (i = 0; i < 10; i++){
    printf("%d ", arr[i]);
  }
  printf("\n");
  return 0;
}
In the example, we have declared an integer array of size 10 . In the next step we are initializing each of the variable of the array with a integer value except the last member. So whenever we are accessing the last member without actually initializing we dont know what actual value is present,it is due to the scope of the array,as it is local variable the default will be garbage.
Valgrind throws error whenever you give the executable to it.
 Compile the application with -g option
gcc -o app app.c -g
Use valgrind command to find out whether there is any error in the code.
valgrind --tool=memcheck --leak-check=yes ./app
O/p of valgrind:

==3728== Memcheck, a memory error detector
==3728== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==3728== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==3728== Command: ./app
==3728== 
==3728== Use of uninitialised value of size 4
==3728==    at 0x40910DB: _itoa_word (_itoa.c:195)
==3728==    by 0x409521A: vfprintf (vfprintf.c:1629)
==3728==    by 0x409BB2E: printf (printf.c:35)
==3728==    by 0x40684D2: (below main) (libc-start.c:226)
==3728== 
==3728== Conditional jump or move depends on uninitialised value(s)
==3728==    at 0x40910E3: _itoa_word (_itoa.c:195)
==3728==    by 0x409521A: vfprintf (vfprintf.c:1629)
==3728==    by 0x409BB2E: printf (printf.c:35)
==3728==    by 0x40684D2: (below main) (libc-start.c:226)
==3728== 
==3728== Conditional jump or move depends on uninitialised value(s)
==3728==    at 0x40960EA: vfprintf (vfprintf.c:1629)
==3728==    by 0x409BB2E: printf (printf.c:35)
==3728==    by 0x40684D2: (below main) (libc-start.c:226)
==3728== 
==3728== Conditional jump or move depends on uninitialised value(s)
==3728==    at 0x4094960: vfprintf (vfprintf.c:1629)
==3728==    by 0x409BB2E: printf (printf.c:35)
==3728==    by 0x40684D2: (below main) (libc-start.c:226)
==3728== 
0 1 2 3 4 5 6 7 8 134513817 
==3728== 
==3728== HEAP SUMMARY:
==3728==     in use at exit: 0 bytes in 0 blocks
==3728==   total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==3728== 
==3728== All heap blocks were freed -- no leaks are possible
==3728== 
==3728== For counts of detected and suppressed errors, rerun with: -v
==3728== Use --track-origins=yes to see where uninitialised values come from
==3728== ERROR SUMMARY: 20 errors from 4 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