內存泄漏定義
內存泄漏指的是在程序裏動態申請的內存在使用完後,沒有進行釋放,導致這部分內存沒有被系統回收,久而久之,可能導致程序內存不斷增大,系統內存不足
內存泄漏危害
- 系統可用內存越來越小
- 機器卡頓
- 系統崩潰
- 排查起來很困難
定位方法
內存泄漏方法有很多種,也可以藉助第三方插件 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函數內第一行是有內存泄漏的,但此時編譯器以及程序運行時不會報任何內存泄漏信息。
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;
}
此時輸出信息會報內存泄漏
3、重新運行程序,在監聽中加入{,,msvcr100d.dll}_crtBreakAlloc,值爲211,程序會在內存泄漏的代碼位置中斷
4、點擊中斷,查看調用堆棧,即可看到內存泄漏代碼位置
5、在相應位置釋放資源即可
VS2015內存泄漏檢測、追蹤方法:
https://blog.csdn.net/lihaidong1991/article/details/103486358