Valgrind

MuYusen 于 2023-10-07 发布 本文总阅读量

Valgrind

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

GUI

ubuntu 安装

sudo apt-get install valgrind

valgrind --version
valgrind-3.18.1

编译程序

运行程序

myprog arg1 arg2

valgrind --leak-check=yes myprog arg1 arg2

实例

一段有内存问题的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)