手工实现一个野指针识别和内存泄漏排查工具

// beforeMain.cpp : 定义控制台应用程序的入口点。
//

#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;
}


WAI 2016/4/27 11:56:50
这是大规模C++程序设计上演示的一个 内存管理工具simple

WAI 2016/4/27 11:57:09
我不知道union可以这么玩的
原文地址:https://www.cnblogs.com/songr/p/5438346.html