博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Valgrind内存泄露检测工具使用初步
阅读量:7100 次
发布时间:2019-06-28

本文共 1927 字,大约阅读时间需要 6 分钟。

一、前言

上次阿里电话面试,被问到了内存泄露的解决办法,但是我只知道智能指针,面试官问我还有其他办法吗,我没答上来。后来一查才知道可以有专门的工具用来检测,今天把这个工具简单实践一下。

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 #include 
2 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操作导致的内存泄露。

转载于:https://www.cnblogs.com/renzhe688/p/3638511.html

你可能感兴趣的文章
重看计算机基础1:数据线、地址线,按字、按字节寻址。
查看>>
oracle 11g亿级复杂SQL优化一例(数量级性能提升)
查看>>
Qt Md5应用示例
查看>>
tensorflow 笔记11:tf.nn.dropout() 的使用
查看>>
路由事件
查看>>
WPF实现选项卡效果(1)——使用AvalonDock
查看>>
字符 16进制 字节 关系
查看>>
C# 给现有PDF文档添加页眉、页脚
查看>>
『算法学习』FPN:feature pyramid networks for object detection
查看>>
K-近邻算法(KNN)
查看>>
java服务端微信小程序支付
查看>>
flip 翻转效果 css3实现
查看>>
Cocos Creater 监听程序到后台和重新到前台
查看>>
Windows 10 应用创建模糊背景窗口的三种方法
查看>>
Python类与标准库
查看>>
学生表、课程表、 成绩表 、教师表sql练习
查看>>
vue inheritAttrs、$attrs和$listeners使用
查看>>
诗歌的分类
查看>>
nexus maven私服搭建
查看>>
系统空间占用排查 tomcat超大日志catalina.out 删除 与df 状态更新
查看>>