Valgrind内存泄露检测工具使用初步
2014-04-01 16:04
639 查看
一、前言
上次阿里电话面试,被问到了内存泄露的解决办法,但是我只知道智能指针,面试官问我还有其他办法吗,我没答上来。后来一查才知道可以有专门的工具用来检测,今天把这个工具简单实践一下。Valgrind是一套可以用于内存检测、线程错误检测、性能分析等的工具集。
memcheck是其中一个内存错误检测器,今天主要学习这个工具。
二、安装
从官网下载源代码并解压:valgrind-3.9.0.tar.bz2gzip2 -d valgrind-3.9.0.tar.bz2 tar 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:#include <stdio.h> void func() { char *temp = new char[100];//memery leak printf("i lose 100 bytes~\n"); } int main() { func(); return 0; }
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操作导致的内存泄露。
相关文章推荐
- linux 下内存泄露检测工具valgrind的使用
- Linux下使用valgrind工具对C++编程检测内存泄露
- valgrind工具的使用,检测内存泄露
- Ubuntu下内存泄露检测工具Valgrind的使用
- Ubuntu下内存泄露检测工具Valgrind的使用
- C/C++内存泄露检测工具 valgrind
- Wince内存泄露检测工具Application Verifier的使用和如何快速定位泄露语句(二)
- linux下内存泄露检测工具Valgrind介绍
- Linux 内存检测工具valgrind使用手册(转)
- 使用Visual Leak Detector for Visual C++ 捕捉内存泄露---Visual C++内存泄露检测—VLD工具使用说明
- valgrind linux内存泄露检测工具
- iPhone Instruments工具使用_检测内存泄露(转)
- Ubuntu下使用valgrind检测内存泄露流程
- 内存泄露检测工具 - Valgrind
- linux 内存泄露检测工具——valgrind
- linux使用valgrind 工具检查内存泄露
- 内存泄露检测工具 - Valgrind
- 内存泄露检测工具valgrind
- JAVA内存泄露检测工具如何使用
- 为什么要使用内存泄露工具、性能检测工具