2014-03-06 48 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