2014-03-06 111 views
2

我正在阅读如何查找与Win32应用程序上的C++ new运算符和标准CRT malloc函数的内存泄漏。调试Win32 API应用程序内存泄漏

我添加了一些与Windows套接字一起工作的东西,我想包括crtdbg.h只有在调试模式下运行,以及其他一些定义。所以我结束了一起拼凑到这一点我stdafx.cpp作为我的标准的预编译的头:

// stdafx.h : include file for standard system include files, 
// or project specific include files that are used frequently, but 
// are changed infrequently 
// 

#pragma once 

#include "targetver.h" 

#define WIN32_LEAN_AND_MEAN    // Exclude rarely-used stuff from Windows headers 
// Windows Header Files: 
#include <windows.h> 

// C RunTime Header Files 
#include <stdlib.h> 
#include <malloc.h> 
#include <memory.h> 
#include <tchar.h> 

// Windows Sockets 
#include <winsock2.h> 
#pragma comment(lib,"ws2_32.lib") 


// If running in debug mode we need to use this library to check for memory leaks, output will be in DEBGUG -> WINDOWS -> OUTPUT 
// http://msdn.microsoft.com/en-us/library/x98tx3cf.aspx 
#ifdef _DEBUG 
    //http://stackoverflow.com/questions/8718758/using-crtdumpmemoryleaks-to-display-data-to-console 
    #ifndef DBG_NEW  
     #define DBG_NEW new (_NORMAL_BLOCK , __FILE__ , __LINE__)  
     #define new DBG_NEW 
    #endif 
    #define _CRTDBG_MAP_ALLOC 
    #include <crtdbg.h> 
#endif // _DEBUG 

我也打算把这些线只是我计划的退出点之前:

#ifdef _DEBUG 
    _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG); 
    _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG); 
    _CrtDumpMemoryLeaks(); 
#endif 

不管怎么说,它似乎编译,但我得到一些奇怪的警告:

警告C4005: '_malloca':宏的重新定义

crtdbg.h。这是由于stdafx.h中标题的顺序错误造成的,或者这是正常的吗?另外,我在正确的轨道上检测Win32应用程序中的内存泄漏,还是在Visual Studio中应该使用其他内容?

+2

也许你应该在包含第一个头文件之前(或者至少在Windows.h之前)定义'_CRTDBG_MAP_ALLOC'。 – Medinoc

+1

您可能感兴趣的[VLD](http://vld.codeplex.com/)(视觉检漏仪) –

回答

2

从crtdbg.h。这是由于stdafx.h中头文件的错误排序导致的,或者这是正常的吗?

也许this article可以帮助你。注意这部分:

为了使CRT功能正常工作,#include语句必须遵循此处显示的顺序。


你可以使用Visual Leak Detector寻找参与的new运营商缺少delete如其他人所说的泄漏。我有很好的经验,但我通常倾向于三重检查,如果在我的代码中每个new都有相应的delete呼叫。


而且,我是在正确的轨道中的Win32应用程序检测内存泄漏或有别的我应该使用在Visual Studio?

其他类型的内存泄漏是GDI leaks。这些通常在您不将device context恢复到原始状态或忘记删除GDI object时发生。我使用GDIView。它的用法很好描述,但如果你有任何问题请留言。

您可能会感兴趣this article有用。

当然,这里有很多好的工具,这只是我的建议。

希望这会有所帮助。

此致敬礼。

+0

第一部分确实是正确的选择。我有同样的问题,今天纠正了,当我意识到stdlib.h包含两次,第一次没有首先定义_CRTDBG_MAP_ALLOC。因此,在MSDN中编写的三行必须按照指定的顺序编写,如果可能的话在所有其他包含之前(避免隐藏包含stdlib)。 – Bentoy13

+0

@ Bentoy13:我很高兴你解决了你的问题:) – AlwaysLearningNewStuff