天天看点

VS2015内存泄漏检测、追踪

之前写了一篇VS2010内存泄漏检测和追踪的方法,最近在2015上发现不太适用(监听找不到msvcr140d.dll),现介绍一个适用2015的方法。

内存泄漏定义

内存泄漏指的是在程序里动态申请的内存在使用完后,没有进行释放,导致这部分内存没有被系统回收,久而久之,可能导致程序内存不断增大,系统内存不足

内存泄漏危害

  • 系统可用内存越来越小
  • 机器卡顿
  • 系统崩溃
  • 排查起来很困难

定位方法

内存泄漏方法有很多种,也可以借助第三方插件 Visual Leak Detector(开源,免费)进行排查,本篇文章介绍一种 借助Visual Studio 调试器和 C 运行时 (CRT) 库进行排查的方法。

1、我们以一个小demo进行分析:

#include "stdafx.h"
#include <string>
 
using namespace std;
class CStudent
{
public:
    CStudent(int age, std::string name) : m_age(age), m_name(name) {}
    ~CStudent() {}
 
    int Age(){return m_age;}
private:
    int m_age;
    std::string m_name;
};
 
void MemoryTest()
{
    CStudent* pStudent = new CStudent(20, "xiaoming");
    int age = pStudent->Age();
}
 
int _tmain(int argc, _TCHAR* argv[])
{
    MemoryTest();
    return 0;
}           

很容易可以发现在MemoryTest函数内第一行是有内存泄漏的,但此时编译器以及程序运行时不会报任何内存泄漏信息。

VS2015内存泄漏检测、追踪

2、加入相关代码

#ifdef _DEBUG
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif
 
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);           
#include "stdafx.h"
#include <string>
 
 
#ifdef _DEBUG
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif
 
class CStudent
{
public:
    CStudent(int age, std::string name) : m_age(age), m_name(name) {}
    ~CStudent() {}
 
    int Age(){return m_age;}
private:
    int m_age;
    std::string m_name;
};
 
void MemoryTest()
{
    CStudent* pStudent = new CStudent(20, "xiaoming");
    int age = pStudent->Age();
}
 
int _tmain(int argc, _TCHAR* argv[])
{
    _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
    MemoryTest();
    return 0;
}           

此时输出信息会报内存泄漏

VS2015内存泄漏检测、追踪

3、重新运行程序,在监听中加入{,,msvcr100d.dll}_crtBreakAlloc,值为225,程序会在内存泄漏的代码位置中断

int _tmain(int argc, _TCHAR* argv[])
{
	_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
	_CrtSetBreakAlloc(225);
	MemoryTest();
	return 0;
}           
VS2015内存泄漏检测、追踪

4、点击中断,查看调用堆栈,即可看到内存泄漏代码位置

VS2015内存泄漏检测、追踪

5、在相应位置释放资源即可

VS2010内存泄漏检测、追踪方法:

https://blog.csdn.net/lihaidong1991/article/details/103486118

继续阅读