3. Introduction
Valgrind:
memory mismanagement detector (memory leaks, deallocation etc.)
tool suite providing a number of debugging tools (eg: Memcheck, by default)
help make your programs faster and more correct
can detect many memory-related error
Memcheck:
memory error detector
4. Preparing Program
compile with ‘-g’ to include debugging information
‘-o0’ can also be used, but slows down the process
using ‘-o1’ speeds up the process but line numbers can be inaccurate
gcc -g test_prog.c -o test_prog.out
5. Running Program
valgrind [valgrind-options] ./prog [prog-args]
valgrind --leak-check=yes --show-reachable=yes --
tool=memcheck --error-limit=no --track-origins=yes
./test_prog.out arg1 arg2 … argN
- --leak-check=yes(yes/no/summary-default) turns on detailed memory leak detector
- --tool=memcheck(default- Cachegrind/Addrgrind/Callgrind/Massif etc)
- --error-limit(yes-default/no) 30000 in total, or 300 different ones
6. Setting Default Options
can be passed through :
file ~/.valgrindrc
environment variable $VALGRIND_OPTS
file ./.valgrindrc
for different valgrind command line options read section: 2.6
7. Error Detection
//test_prog.c
int main()
{
char *p;
// Allocation #1 of 19 bytes
p = (char *) malloc(19);
// Allocation #2 of 12 bytes
p = (char *) malloc(12);
free(p);
// Allocation #3 of 16 bytes
p = (char *) malloc(16);
return 0;
}
9. Illegal Address
#include <stdio.h>
#include <stdlib.h>
int main(){
int *arr = malloc(20);
int i;
for(i = 0; i<5; i++){
arr[i] = i;
}
free(arr);
printf("%dn", arr[2]);
return 0;}
10. Use of Uninitialised Values
#include <stdio.h>
int main(){
int x;
printf("%dn", x);
return 0;
}
11. Use of Uninitialised Values(Contd.)
void func(int y){
if(y==2)printf("OKn");
else printf("Wrongn");
}
int main(){
int x;
func(x);
return 0;
}
12. Proviso
can’t detect all errors
an instance:
int main(){
int i;
int x =0;
int a[10];
for (i = 0; i < 11; i++) a[i] = i;
printf("%dn", a[10]);
return 0;
}