zl程序教程

您现在的位置是:首页 >  硬件

当前栏目

使用 CRT 库查找内存泄漏

内存 查找 泄漏 CRT 使用
2023-09-27 14:28:31 时间

使用 CRT 库查找内存泄漏 - Visual Studio (Windows) | Microsoft Docs

#define _CRTDBG_MAP_ALLOC // 显示跟详细,显示首次分配泄漏的内存的文件名和行号
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
#include <string>

using namespace std;
int main()
{
    int* p = (int*)malloc(sizeof(int));
    free p;
    _CrtDumpMemoryLeaks();	// 在应用退出时显示内存泄漏报告
    return 0;
}

在这里插入图片描述

对于C++中new/delete也可以使用上述操作方法,唯一的缺陷就是输出的报告中不展示泄露所在的文件中代码所在行数。
在这里插入图片描述
docs.microsoft 给出的方法是,使用下列宏来报告执行分配的行。

// debug_new.cpp
// compile by using: cl /EHsc /W4 /D_DEBUG /MDd debug_new.cpp
#define _CRTDBG_MAP_ALLOC
#include <cstdlib>
#include <crtdbg.h>

#ifdef _DEBUG
    #define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
    // Replace _NORMAL_BLOCK with _CLIENT_BLOCK if you want the
    // allocations to be of _CLIENT_BLOCK type
#else
    #define DBG_NEW new
#endif

struct Pod {
    int x;
};

void main() {
    Pod* pPod = DBG_NEW Pod;
    pPod = DBG_NEW Pod; // Oops, leaked the original pPod!
    delete pPod;

    _CrtDumpMemoryLeaks();
}

在这里插入图片描述