The Valgrind tool suite provides a number of debugging and profiling tools that help you make your programs faster and more correct. The most popular of these tools is called Memcheck.
2. Preparing your programCompile your program with -g to include debugging information so that Memcheck's error messages include exact line numbers. Using -O0 is also a good idea, if you can tolerate the slowdown.
3. Running your program under MemcheckSYNOPSIS
valgrind [valgrind-options] [your-program] [your-program-options]
Memcheck is the default tool.
examples:
valgrind --leak-check=yes myprog arg1 arg2
输出信息格式为[进程号][描述信息]
常用的错误信息使用注意现象
1 由于没有 -g 参数编译,所以无法定位到具体的代码位置,处理方法是添加上 -g 开关后重新编译
==2369== at 0x8054575: update_terminal_stata (in /home/key/p4v/udp-server/udpsc/sc/udp-srv/udp-server)
==2369== by 0x805478B: thrd_loop_hash_list_entry (in /home/key/p4v/udp-server/udpsc/sc/udp-srv/udp-server)
==2369== by 0x4EACDAFE: start_thread (in /usr/lib/libpthread-2.16.so)
==2369== by 0x4E9FD0ED: clone (in /usr/lib/libc-2.16.so)
==2369== Address 0x4350978 is 0 bytes after a block of size 1,024 alloc'd
==2369== at 0x4008E28: malloc (vg_replace_malloc.c:270)
==2369== by 0x8054352: update_terminal_stata (in /home/key/p4v/udp-server/udpsc/sc/udp-srv/udp-server)
==2369== by 0x805478B: thrd_loop_hash_list_entry (in /home/key/p4v/udp-server/udpsc/sc/udp-srv/udp-server)
==2369== by 0x4EACDAFE: start_thread (in /usr/lib/libpthread-2.16.so)
==2369== by 0x4E9FD0ED: clone (in /usr/lib/libc-2.16.so)
==2369==
==4401== Invalid write of size 1
==4401== at 0x80484B6: lstrcat (strcat.c:9)
==4401== by 0x804851B: main (strcat.c:20)
==4401== Address 0x4027030 is 0 bytes after a block of size 8 alloc'd
==4401== at 0x4008E28: malloc (vg_replace_malloc.c:270)
==4401== by 0x80484E8: main (strcat.c:15)
这里是指内存越界的错误提示,而是是使用 malloc 这种内存申请的内存块出错,如果是一个
下面的代码在valgrind 的memmory check中是不会报错的
char buff[8]={0};
strcpy(buff,"123456789");
如果A处代码向buff写入时发生越界,那么每次读取buff的时候,就都会报这种错误
4 memory leak
==4576== HEAP SUMMARY:
==4576== in use at exit: 8 bytes in 1 blocks
==4576== total heap usage: 1 allocs, 0 frees, 8 bytes allocated
==4576==
==4576== 8 bytes in 1 blocks are definitely lost in loss record 1 of 1
==4576== at 0x4008E28: malloc (vg_replace_malloc.c:270)
==4576== by 0x80484B8: main (strcat.c:15)
valgrind --leak-check=yes ./ap
否则的话只会看到这样的效果
==4610== HEAP SUMMARY:
==4610== in use at exit: 8 bytes in 1 blocks
==4610== total heap usage: 1 allocs, 0 frees, 8 bytes allocated