内存管理工具,帮助检查内存泄露及野指针问题
2021/6/29 7:20:51
本文主要是介绍内存管理工具,帮助检查内存泄露及野指针问题,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
转载: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;
}
这篇关于内存管理工具,帮助检查内存泄露及野指针问题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-26Java语音识别项目资料:新手入门教程
- 2024-11-26JAVA语音识别项目资料:新手入门教程
- 2024-11-26Java语音识别项目资料:入门与实践指南
- 2024-11-26Java云原生资料入门教程
- 2024-11-26Java云原生资料入门教程
- 2024-11-26Java云原生资料:新手入门教程
- 2024-11-25Java创意资料:新手入门的创意学习指南
- 2024-11-25JAVA对接阿里云智能语音服务资料详解:新手入门指南
- 2024-11-25Java对接阿里云智能语音服务资料详解
- 2024-11-25Java对接阿里云智能语音服务资料详解