对C、C++的内存泄露、内存溢出等检查,经过这两天的查资料,总体来说可以使用Valgrind, AddressSanitizer, Dr.Memory等。其中Valgrind对程序运行速度影响较大,运行耗时10倍以上,如果是对Android Native代码进行检查,比较推荐对代码进行必要的修改,编译成可执行文件,在pc Linux系统上检测是否存在内存问题。Dr.Memory则比Valgrind的速度快,比较适合在Windows系统中使用。而对于Android上的使用,Google目前则大力推荐使用AddressSanitizer来替代Valgrind.

Dr.Memory使用

IBM developer一个较好的case

Valgrind使用

参考

参考2

Valgrind包含下列工具:

  1. memcheck:检查程序中的内存问题,如泄漏、越界、非法指针等。
  2. callgrind:检测程序代码的运行时间和调用过程,以及分析程序性能。
  3. cachegrind:分析CPU的cache命中率、丢失率,用于进行代码优化。
  4. helgrind:用于检查多线程程序的竞态条件。
  5. massif:堆栈分析器,指示程序中使用了多少堆内存等信息。
  6. lackey:
  7. nulgrind:

    这几个工具的使用是通过命令:valgrand --tool=name 程序名来分别调用的,当不指定tool参数时默认是 --tool=memcheck.

使用:

  1. 在Ubuntu中下载安装Valgrind,sudo apt install valgrind
  2. 把要检测的代码编译成可执行文件,注意编译的时候要带上-g编译命令。比如g++ -g -o testValgrind testValgrind.cpp
  3. 使用Valgrind来检测,valgrind --tool=memcheck --leak-check=full ./testValgrind

AddressSanitizer

这是谷歌目前极力推荐在Android中使用的内存检测工具

VisualStudio检测

如果使用VisualStudio,则有更为简单的方法做一内存泄露检测,但也只能检测内存泄露。代码如下,[参考](c++怎么检测内存泄露,怎么定位内存泄露? - Chen Moore的回答 - 知乎

https://www.zhihu.com/question/63946754/answer/214793614):

/*
* 1:在每个cpp文件中包含base.h头文件,当然直接把base.h的内容复制到cpp中也可以
* 2:在程序退出的时候调用_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
* 3:在VS的debug模式下
*/
#include "base.h"
#include "stdafx.h"
#include <iostream> int main()
{
int *a = new int[8];
int *b = (int *)malloc(8 * 7);
a[0] = 5;
a[9] = 99;
std::cout << a[0]; _CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF);
return 0;
} /*
//base.h内容
#ifdef _WIN32
#include <crtdbg.h>
#ifdef _DEBUG
#define new new(_NORMAL_BLOCK,__FILE__,__LINE__)
#endif
#endif #ifdef _WIN32
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
#endif
*/

最新文章

  1. 常用的sublime text插件(很爽哦)
  2. 简单的STM32 汇编程序—闪烁LED
  3. AC日记——找最大数序列 openjudge 1.9 10
  4. Windows应用层网络模块扫盲
  5. IT服务系统组成
  6. c++ 设计模式5 (Observer / Event 观察者模式)
  7. 【分享】.Net有哪些大型项目、大型网站的案例?
  8. MFC控件(8):command button与syslink control
  9. Xcode7修改模块生成网络权限(ATS配置)
  10. asp.net客户端IP跟踪
  11. 用 LSTM 做时间序列预测的一个小例子(转自简书)
  12. JAVA作业三
  13. 线程安全问题.md
  14. Python全栈-day8-day9-函数1
  15. collections, time, queue的应用
  16. Asp.Net_HttpModule的应用
  17. linux下挂载VHD等虚拟磁盘文件
  18. [CSS] Collapsing Margins
  19. c++刷题(6/100)最长上升子序列
  20. Oracle数据库,简单SQL练习与答案

热门文章

  1. 在vue中使用svg sprite
  2. [Swift]LeetCode523. 连续的子数组和 | Continuous Subarray Sum
  3. [Swift]LeetCode721. 账户合并 | Accounts Merge
  4. [Swift]LeetCode801. 使序列递增的最小交换次数 | Minimum Swaps To Make Sequences Increasing
  5. Linux(Ubuntu) OpenGL 开发环境
  6. restful风格的API
  7. .Net 调用中国气象台Web Service
  8. Qt5模块简介
  9. solr索引报错(java.lang.OutOfMemoryError:GC overhead limit exceeded)
  10. SpringBoot入门教程(十八)@value、@Import、@ImportResource、@PropertySource