_CRTDBG_MAP_ALLOC 不显示文件名和行号

_CRTDBG_MAP_ALLOC not showing file name and line number

我使用 Visual Studio 2017。我使用转储内存泄漏的动态库:_CrtDumpMemoryLeaks(); 我添加了适当的宏定义:

#define _CRTDBG_MAP_ALLOC

但输出仍然不包含文件名和行号。当我调试那个 dll 时,我可以进入 以下 malloc 定义:

//
// malloc.cpp
//
//      Copyright (c) Microsoft Corporation. All rights reserved.
//
// Implementation of malloc().
//
#include <corecrt_internal.h>
#include <malloc.h>



// Allocates a block of memory of size 'size' bytes in the heap.  If allocation
// fails, nullptr is returned.
//
// This function supports patching and therefore must be marked noinline.
// Both _malloc_dbg and _malloc_base must also be marked noinline
// to prevent identical COMDAT folding from substituting calls to malloc
// with either other function or vice versa.
extern "C" _CRT_HYBRIDPATCHABLE __declspec(noinline) _CRTRESTRICT void* __cdecl malloc(size_t const size)
{
    #ifdef _DEBUG
    return _malloc_dbg(size, _NORMAL_BLOCK, nullptr, 0);
    #else
    return _malloc_base(size);
    #endif
}

另一方面,当我在 Visual Studio 中创建一个简单的控制台应用程序时,我无法进入 malloc,但内存泄漏输出显示文件名和行号。这是怎么回事 ?如何解决?

文档中描述的技术 Find memory leaks with the CRT library

关键是你需要在任何#include:

之前添加以下3行
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>