1.2 内存泄漏
int main()
{
int size = 0;
try
{
while (1)
{
//int* p = (int*)malloc(sizeof(int) * 1024 * 1024);
/*if (p == NULL)
{
break;
}*/
int* p = new int[1024 * 1024];
size = size + 4 * 1024 * 1024;
cout << p << endl;
}
}
catch (const exception& e)
{
cout << e.what() << endl;
}
cout << size/1024/1024 << "MB" << endl;
return 0;
}
1.2.1 什么是内存泄漏,内存泄漏的危害
void MemoryLeaks()
{
// 1.内存申请了忘记释放
int* p1 = (int*)malloc(sizeof(int));
int* p2 = new int;
// 2.异常安全问题
int* p3 = new int[10];
Func(); // 这里Func函数抛异常导致 delete[] p3未执行,p3没被释放.
delete[] p3;
}
1.2.2 内存泄漏分类
1.2.3 如何检测内存泄漏
int main()
{
int* p = new int[10];
// 将该函数放在main函数之后,每次程序退出的时候就会检测是否存在内存泄漏
_CrtDumpMemoryLeaks();
return 0;
}
// 程序退出后,在输出窗口中可以检测到泄漏了多少字节,但是没有具体的位置
Detected memory leaks!
Dumping objects ->
{79} normal block at 0x00EC5FB8, 40 bytes long.
Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
Object dump complete.
- 在linux下内存泄漏检测:linux下几款内存泄漏检测工具
- 在windows下使用第三方工具:VLD工具说明
- 其他工具:内存泄漏工具比较
1.2.4如何避免内存泄漏