声明:checkleaks.h和checkleaks.cpp这两个文件中的代码是在网上COPY的,但原来那个网站现在却找不到了
所以,这篇文章不算完全原创,呵呵。
就当作是一个存档吧
先上代码:
- #ifndef SET_DEBUG_NEW_H
- #define SET_DEBUG_NEW_H
-
- #ifdef _DEBUG
- #define DEBUG_CLIENTBLOCK new( _CLIENT_BLOCK, __FILE__, __LINE__)
- #else
- #define DEBUG_CLIENTBLOCK
- #endif
-
- #define _CRTDBG_MAP_ALLOC
- #include <crtdbg.h>
-
- #ifdef _DEBUG
- #define new DEBUG_CLIENTBLOCK
- #endif
-
- #pragma once
-
- #if defined(WIN32)
- void setFilterDebugHook(void);
- #endif
-
- #endif
-
-
- #if defined(WIN32)
-
- #include <string.h>
- #include "crtdbg.h"
-
- #define FALSE 0
- #define TRUE 1
-
- _CRT_REPORT_HOOK prevHook;
-
- int reportingHook(int reportType, char* userMessage, int* retVal)
- {
-
-
-
-
- const int numFollowupDebugMsgParts = 2;
- static bool ignoreMessage = false;
- static int debugMsgPartsCount = 0;
-
-
- if ((strncmp(userMessage,"Detected memory leaks!/n", 10) == 0)
- || ignoreMessage)
- {
-
- if (strncmp(userMessage,"Object dump complete./n", 10) == 0)
- {
- _CrtSetReportHook(prevHook);
- ignoreMessage = false;
- } else
- ignoreMessage = true;
-
-
- if(strstr(userMessage, ".cpp") == NULL)
- {
- if(debugMsgPartsCount++ < numFollowupDebugMsgParts)
-
- return FALSE;
- else
- return TRUE;
- } else
- {
- debugMsgPartsCount = 0;
-
- return FALSE;
- }
- } else
-
- return FALSE;
- };
-
- void setFilterDebugHook(void)
- {
-
- prevHook = _CrtSetReportHook(reportingHook);
- }
-
- #endif
-
-
- #include <windows.h>
- #include <stdio.h>
- #include "checkleaks.h"
-
- int main()
- {
-
- _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
- int *arr;
- arr = new int;
- return 0;
- }
程序输出:
- Detected memory leaks!
- Dumping objects ->
- e:\vs2008\try\ctemp\ctemp\main.cpp(9) : {62} client block at 0x00503DE8, subtype 0, 4 bytes long.
- Data: < > CD CD CD CD
- Object dump complete.
- The program ‘[3348] ctemp.exe: Native‘ has exited with code 0 (0x0).
http://blog.csdn.net/small_qch/article/details/6856445
在VC中检测内存泄漏
原文:http://www.cnblogs.com/findumars/p/4851483.html