一、前言
上次阿里电话面试,被问到了内存泄露的解决办法,但是我只知道智能指针,面试官问我还有其他办法吗,我没答上来。后来一查才知道可以有专门的工具用来检测,今天把这个工具简单实践一下。
Valgrind是一套可以用于内存检测、线程错误检测、性能分析等的工具集。
memcheck是其中一个内存错误检测器,今天主要学习这个工具。
二、安装
从下载源代码并解压:valgrind-3.9.0.tar.bz2
gzip2 -d valgrind-3.9.0.tar.bz2tar xvf valgrind-3.9.0.tar
安装:
./autogen.sh./configure --prefix=/usr/bin/valgrind./make./make install
最后测试是否成功:
./valgrind ls -l
三、Memcheck使用
1.所需的编译选项
1.用-g
使目标文件保存调试信息(行号等)
2.用-O0
或-O1
优化选项,-O0
最准确但速度慢,-O1
可能不准确但速度快,通常效果也不错。
2.检测内存泄露
./valgrind --leak-check=full ./a.out
3.例子
test.c:
1 #include2 void func() 3 { 4 char *temp = new char[100];//memery leak 5 printf("i lose 100 bytes~\n"); 6 } 7 8 int main() 9 {10 func();11 return 0;12 }
gcc -g -o test test.c
用valgrind运行程序:
./valgrind --leak-check=full ./test
结果如下:
==25108== Memcheck, a memory error detector==25108== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.==25108== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info==25108== Command: ./test==25108== ==25108== ==25108== HEAP SUMMARY:==25108== in use at exit: 100 bytes in 1 blocks==25108== total heap usage: 1 allocs, 0 frees, 100 bytes allocated==25108== ==25108== 100 bytes in 1 blocks are definitely lost in loss record 1 of 1==25108== at 0x40078C6: operator new[](unsigned int) (vg_replace_malloc.c:357)==25108== by 0x80484D5: func() (test.cc:5)==25108== by 0x80484F1: main (test.cc:11)==25108== ==25108== LEAK SUMMARY:==25108== definitely lost: 100 bytes in 1 blocks==25108== indirectly lost: 0 bytes in 0 blocks==25108== possibly lost: 0 bytes in 0 blocks==25108== still reachable: 0 bytes in 0 blocks==25108== suppressed: 0 bytes in 0 blocks==25108== ==25108== For counts of detected and suppressed errors, rerun with: -v==25108== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 15 from 8)
从中可以发现是在func()中new操作导致的内存泄露。