内存管理工具,帮助检查内存泄露及野指针问题
作者:互联网
转载:https://www.cnblogs.com/songr/p/5438346.html
#include "stdafx.h"
#include <iostream>
using namespace std;
union Align;
class CTest
{
public:
int A;
double B;
CTest()
{
cout<<"构造函数"<<endl;
}
~CTest()
{
cout<<"析构"<<endl;
}
};
union Align
{
struct
{
int a;
int b;
} data;
long double ld;//确保开辟8个字节空间
};
static unsigned totalMemoryBlock = 0;
static unsigned totalMemorySize = 0;
//重载new操作符
static void* operator new(size_t size)
{
Align* align = (Align* )new char[sizeof(Align) + size ];
align->data.a = 0x1234;
align->data.b = size;
totalMemorySize += size; //记录内存分配
totalMemoryBlock++;
++align;
void* result = align;
cout<<"operator new "<<endl;
return result;
}
static void operator delete(void* _Ptr)
{
if (_Ptr == NULL)
{
cout<<"无法释放空指针"<<endl;
return;
}
Align* align = (Align*)_Ptr;
if (align[-1].data.a == 0x1234)
{
cout<<"内存有效"<<endl;
align[-1].data.a = 0x4321;
totalMemorySize -= align[-1].data.b;
totalMemoryBlock--;
delete[] (char*)--align;
}
else
{
cout<<"内存无效无法释放!野指针释放"<<endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
CTest* t1 = new CTest();
CTest* t2 = new CTest();
delete t1;
delete t2;
delete t1;
delete t1;
delete t1;
CTest* t3 = new CTest();
if (totalMemoryBlock > 0)
{
cout<<"内存泄漏!"<<endl;
cout<<"泄漏大小 "<<totalMemorySize<<"字节"<<endl;
}
system("pause");
return 0;
}
标签:cout,align,管理工具,及野,内存,new,Align,CTest,delete 来源: https://www.cnblogs.com/Lucky-qin2013/p/14947930.html