About
Valgrind是一个用于构建动态分析工具的框架。Valgrind工具可以自动检测许多内存管理和线程错误,并详细分析你的程序。你也可以使用Valgrind构建新工具。
The Valgrind distribution currently includes seven production-quality tools: a memory error detector, two thread error detectors, a cache and branch-prediction profiler, a call-graph generating cache and branch-prediction profiler, and two different heap profilers. It also includes an experimental SimPoint basic block vector generator.
Valgrind’s Tool Suite
Memcheck
is a memory error detector. It helps you make your programs, particularly those written in C and C++, more correct.Cachegrind
is a cache and branch-prediction profiler. It helps you make your programs run faster.Callgrind
is a call-graph generating cache profiler. It has some overlap with Cachegrind, but also gathers some information that Cachegrind does not.Helgrind
is a thread error detector. It helps you make your multi-threaded programs more correct.DRD
is also a thread error detector. It is similar to Helgrind but uses different analysis techniques and so may find different problems.Massif
is a heap profiler. It helps you make your programs use less memory.DHAT
is a different kind of heap profiler. It helps you understand issues of block lifetimes, block utilisation, and layout inefficiencies.BBV
is an experimental SimPoint basic block vector generator. It is useful to people doing computer architecture research and development.
GUI
Valkyrie
ubuntu 安装
sudo apt-get install valgrind
valgrind --version
valgrind-3.18.1
编译程序
- 使用
-g
参数编译程序可以包含调试信息,这样可以在Memcheck的错误信息中包含准确的行号 -O0
速度会慢些-O1
错误信息中的行号可能不准确,比-O0
的速度快,但是运行Memcheck的效果相当好- 不建议使用
-O2
及以上版本,因为Memcheck偶尔会报告不存在的未初始化值错误。
运行程序
myprog arg1 arg2
valgrind --leak-check=yes myprog arg1 arg2
- Memcheck是默认工具,
--leak-check
选项打开详细的内存泄漏检测器。
实例
一段有内存问题的C代码
#include <stdlib.h>
void f(void)
{
int* x = malloc(10 * sizeof(int));
x[10] = 0; // problem 1: heap block overrun
} // problem 2: memory leak -- x not freed
int main(void)
{
f();
return 0;
}
## 编译
gcc -o example example.c -g
## 运行
valgrind --leak-check=yes ./example 1 2
## 输出
==22116== Invalid write of size 4
==22116== at 0x10916B: f (example.c:6)
==22116== by 0x109180: main (example.c:11)
==22116== Address 0x4a99068 is 0 bytes after a block of size 40 alloc'd
==22116== at 0x4848899: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==22116== by 0x10915E: f (example.c:5)
==22116== by 0x109180: main (example.c:11)
- 22116 : 进程ID,通常不重要
- Invalid write : 错误类型