内存泄漏定义
内存泄漏指的是在程序里动态申请的内存在使用完后,没有进行释放,导致这部分内存没有被系统回收,久而久之,可能导致程序内存不断增大,系统内存不足
内存泄漏危害
- 系统可用内存越来越小
- 机器卡顿
- 系统崩溃
- 排查起来很困难
定位方法
内存泄漏方法有很多种,也可以借助第三方插件 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函数内第一行是有内存泄漏的,但此时编译器以及程序运行