You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用crtdbg.h检测内存泄漏时为何无法显示代码行号?

内存泄漏无法定位代码行号的解决方法

问题现状

运行Debug版本程序时,系统仅输出泄漏对象的内存地址,无法定位到对应的代码行号。已按教程定义_CRTDBG_MAP_ALLOC宏,但问题仍未解决。

相关代码

#include "main.h"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
#include <math.h>
#include "Store.h"

// TODO
// Change this number to the line number the Output window shows you
// to follow a memory leak. Put -1 to disable.
#define MEMORY_LEAK_LINE -1

void ScopeMain()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    _CrtSetBreakAlloc(MEMORY_LEAK_LINE); // DO NOT COMMENT OUT THIS LINE
    _CrtDumpMemoryLeaks();

    Store* s = new Store();
    s->Print(); 
}

输出窗口截图

Debug输出窗口的内存泄漏信息

解决步骤

  • 调整宏定义位置:_CRTDBG_MAP_ALLOC必须在所有头文件包含之前定义,否则无法正确映射CRT内存分配函数。修改代码开头:

    #define _CRTDBG_MAP_ALLOC
    #include "main.h"
    #include <stdlib.h>
    #include <crtdbg.h>
    #include <iostream>
    #include <math.h>
    #include "Store.h"
    
  • 修正_CrtDumpMemoryLeaks()调用时机:当前调用在泄漏对象创建前执行,此时还不存在内存泄漏。需将其移到对象生命周期结束后:

    void ScopeMain()
    {
        _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
        _CrtSetBreakAlloc(MEMORY_LEAK_LINE);
    
        Store* s = new Store();
        s->Print(); 
    
        _CrtDumpMemoryLeaks(); // 移至此处,确保泄漏已发生
    }
    
  • 跟踪C++的new操作:若上述调整后仍无行号,需确保new操作被CRT调试版本跟踪。在代码全局位置添加如下重载:

    #ifdef _DEBUG
    #define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
    #define new DEBUG_NEW
    #endif
    

    此代码会让所有new操作自动记录文件和行号信息。

额外提示

  • 确保项目处于Debug编译模式,Release模式下CRT调试功能不生效。
  • 若Store类内部存在动态内存分配,需确保其内部内存操作也被正确跟踪。

内容的提问来源于stack exchange,提问作者user21126156

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 11:23:14