系统环境
- Ubuntu 22.10 kinetic
简单介绍
Valgrind是一套 Linux 下的 Debug 工具,常用于检测程序内存泄漏,非法读写等问题。
维基百科 - Valgrind - Wikipedia
本文主要介绍 Memcheck,可以用于检查程序的内存泄漏情况。
安装 Valgrind
官方下载地址 - Valgrind Download
BASH
sudo apt update && apt full-upgrade -y
sudo apt install valgrind -y
valgrind --version
使用方法
BASH
valgrind ./<filename>
valgrind --leak-check=<no|summary|yes|full> [default: summary]
常见错误
1.非法读写错误
C
#include <stdio.h>
int main(){
int *ptr = 0;
*ptr = 0;
return 0;
}
BASH
gcc -g -O0 test.c -o test
./test
[1] 7453 segmentation fault (core dumped) ./test
valgrind ./test
==7484== Memcheck, a memory error detector
==7484== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==7484== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==7484== Command: ./test
==7484==
==7484== Invalid write of size 4
==7484== at 0x10913D: main (test.c:4)
==7484== Address 0x0 is not stack'd, malloc'd or (recently) free'd
2.访问未初始化值
C
#include <stdio.h>
int main(){
int x;
printf ("x = %d\n", x);
}
CodeBlock Loading...
3 在系统调用中使用未初始化或不可寻址的值
CodeBlock Loading...
CodeBlock Loading...
4.非法释放内存
CodeBlock Loading...
CodeBlock Loading...
5.操作符不匹配
如果用 malloc/calloc/realloc/valloc/memalign 分配,则必须使用 free 释放。
如果用 new 分配,则必须用 delete 释放。
如果用 new[] 分配,则必须用 delete[] 释放。
需要注意的是在 Linux 中运行这样的程序是不会有任何问题, 但可能会在其他的平台上崩溃。
CodeBlock Loading...
CodeBlock Loading...
6.内存重叠错误
(Memory Overlapping Error)
使用 memcpy, strcpy, strncpy, strcat, strncat 时会出现的 memory overlap 错误
CodeBlock Loading...
CodeBlock Loading...
7.可疑的参数值
(Fishy argument values)
CodeBlock Loading...
CodeBlock Loading...
8.内存泄漏检测
CodeBlock Loading...
CodeBlock Loading...