zoukankan      html  css  js  c++  java
  • 内存管理工具,帮助检查内存泄露及野指针问题

    转载: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;
    }

  • 相关阅读:
    C++实现邮件群发的方法
    HTML5 Canvas彩色小球碰撞运动特效
    ListView灵活的用法
    Win10计算器在哪里?三种可以打开Win10计算器的方法图文介绍
    设置Textview最大长度,超出显示省略号
    jQuery页面顶部下拉广告
    C#截屏
    细数人们对安卓的误解
    javaScript系列:js中获取时间new Date()详细介绍
    C# 发送Http请求
  • 原文地址:https://www.cnblogs.com/Lucky-qin2013/p/14947930.html
Copyright © 2011-2022 走看看