3

我最近使用指向 s 的原始指针转换了一个程序,std::shared_ptr并希望确保没有内存泄漏。我查看了 MSDN 的使用 CRT 库页面查找内存泄漏,并按照说明设置报告。

我首先将这些行添加到我的文件中:

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

并调用报告 -_CrtDumpMemoryLeaks();

我确实在使用new来分配我的内存,所以,正如页面所示,我添加了......

#ifdef _DEBUG   
#ifndef DBG_NEW      
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )      
#define new DBG_NEW   
#endif
#endif  // _DEBUG

在更精确的泄漏位置方面没有显着变化。相反,我的报告仍然如下所示:

Detected memory leaks!
Dumping objects ->
{158} normal block at 0x006F8458, 8 bytes long.
 Data: <  ,     > DC F6 2C 00 00 00 00 00 
{155} normal block at 0x006FAD40, 40 bytes long.
 Data: <L>              > 4C 3E 17 01 03 00 00 00 01 00 00 00 CD CD CD CD 
{154} normal block at 0x006FAB68, 16 bytes long.
 Data: <d>              > 64 3E 17 01 01 00 00 00 01 00 00 00 00 00 00 00 
{149} normal block at 0x006FAC08, 40 bytes long.
 Data: <L>              > 4C 3E 17 01 03 00 00 00 01 00 00 00 CD CD CD CD 
{148} normal block at 0x006FABB8, 16 bytes long.
 Data: <d>              > 64 3E 17 01 01 00 00 00 01 00 00 00 00 00 00 00 
Object dump complete.
The program '[7152] List.exe' has exited with code 0 (0x0).

不幸的是,该报告是在退出之前生成的,因此无法实时查看泄漏。

通过查看这个问题的答案,我注意到我没有加载 pdb 文件,因为它是一个空项目。所以我遵循了这里给出的建议,它确实解决了 pdb 问题,但未能解决我的问题。

该应用程序是从空控制台应用程序生成的,如果这很重要,我正在以管理员身份运行。

此外,我知道我可以使用外部工具,但我经常使用我无权添加任何工具的计算机,因此让 VS 正常运行是理想的解决方案。让报告显示泄漏的行号的任何帮助都会很棒。

边注:

我想一个合乎逻辑的问题是 - 如果您使用托管指针,为什么我仍然有内存泄漏?好吧,我留下了几个本地化的指针,它们只是各种临时持有者等,似乎不应该引起问题。所以,我觉得我知道它发生在哪里,但这是一个如此简单的程序,我想知道它是如何完成的,所以我可以在更大的程序上使用它。谢谢。

4

3 回答 3

1

您需要确保 stdlib 的定义和包含在应用程序中的任何其他包含之前。

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#ifdef _DEBUG
#ifndef DBG_NEW
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#define new DBG_NEW
#endif
#endif  // _DEBUG

应该是您应用程序中的第一件事。

于 2015-10-02T08:28:47.883 回答
0

您必须验证您在项目中声明的所有类是否包括 crtdbg.h 和宏 _crtdbg_map_alloc 以及最后的报告。

于 2021-01-15T16:45:23.623 回答
0

我发现我必须把

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

每个可能是分配的潜在来源的文件中。我假设我只需要在主程序中执行此操作

_CrtDumpMemoryLeaks();

叫做。

于 2021-03-28T14:26:42.357 回答