内容很簡單,感覺用的話可以下。
- 記憶體洩露的發生的常見情況
- 釋放超出範圍(忘記釋放)
void TestFuc()
{
int *i = new int; //沒有釋放
*i = 11;
}
或者
{
char* str = new char[100]; //沒有釋放
strcpy(str,"memory leak");
}
2. 丢失指針
class TestClass {
int* val;
public: TestClass() { val = new int; *val = 11; } ~TestClass() { delete val; } }; void foo() { TestClass* a = new TestClass; TestClass* b = new TestClass; a = b; delete a; // 已删除 //delete b; //重複删除
}
3. 錯誤的使用new/delete
double* d = new double[12]; delete d; // delete d[0]; // 必須使用 delete [] d;
4. 錯誤釋放
int *i; while(someCondition) {
i = new int;
//其他代碼 } delete i;
注:比較複雜的是多個對象公用一個new的對象,釋放要小心。
- 如何找的記憶體洩露的代碼
- 在使用CPP檔案中使用
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
2. 使用'_CRTDBG_MAP_ALLOC'
#include <iostream>
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
int main()
{
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
int* array = new int[10];
return 0;
}
3. 隻有猜測了, 但然也可以借助一些工具。
注:切莫在一個H檔案中配置設定一個空間int *p = new int(p變量可以被外部使用),并在H檔案中釋放delete p;可是另一處W檔案調用p = NULL。