使用valgrind进行内存泄漏和非法内存操作检测

时间:2021-09-12 02:56:25

valgrind是一个强大的工具,最常用的功能是用它来检测内存泄漏和非法内存的使用。要想让valgrind报告的更加细致,请使用-g进行编译。

基本命令如下:

$ valgrind --tool=memcheck --leak-check=yes program

可以检测如下问题:

1. 如果malloc/realloc/calloc和free的数量不同,则会报告如下的内容。

==3375== HEAP SUMMARY:
==3375== in use at exit: 128 bytes in 1 blocks
==3375== total heap usage: 4,900 allocs, 4,899 frees, 29,477,380 bytes allocated

2. 如果有第一个问题,则会报告哪里申请的内存没有进行释放:

==3375== 128 bytes in 1 blocks are definitely lost in loss record 1 of 1
==3375== at 0x4C2AC3D: dd (d.c:299)
==3375== by 0x50C44F2: cc (c.c:112)
==3375== by 0x5211824: bb (b.c:526)
==3375== by 0x518643B: aa (a.c:398)
==3375== by 0x400EB3: main (main.c:37)

如上表示在文件d.c的299行,有申请内存,没有进行释放。

3. 使用未初始化的变量:

==3375== Conditional jump or move depends on uninitialised value(s)
==3375== at 0x5121568: bb (b.c:1035)
==3375== by 0x511DE92: aa (a.c:60)
==3375== by 0x400FB3: main (main.c:64)

如上说明,在b.c文件的1035行,使用了未初始化的变量。

4. 多次free的问题

==3375== Invalid free() / delete / delete[] / realloc()
==3375== at 0x4C2BD57: free (vg_replace_malloc.c:530)
==3375== by 0x4005AA: aa (a.c:9)
==3375== by 0x4005BA: main (main.c:14)

如上表示,在a.c文件的9行,进行了第2次的free调用。同时也会有如下的提示,表明申请与释放的次数不同。

==3375== HEAP SUMMARY:
==3375== in use at exit: 0 bytes in 0 blocks
==3375== total heap usage: 1 allocs, 2 frees, 4 bytes allocated

5. 非法内存操作:

==3375== Invalid write of size 4
==3375== at 0x40059B: aa (a.c:8)
==3375== by 0x4005BC: main (main.c:14)
==3375== Address 0x51fc044 is 0 bytes after a block of size 4 alloc'd
==3375== at 0x4C2AC3D: malloc (vg_replace_malloc.c:299)
==3375== by 0x40058E: aa (a.c:7)
==3375== by 0x4005BC: main (main.c:14)

如上表示,使用malloc申请了4个字节的内存,但在a.c的第8行,对第4(从0开始计数)个字节进行了写操作。

valgrind主要检测的是动态内存相关的错误。当然valgrind也只是个工具。应该在平时写代码时组织好代码。