声明:checkleaks.h和checkleaks.cpp这两个文件中的代码是在网上COPY的,但原来那个网站现在却找不到了
所以,这篇文章不算完全原创,呵呵。
就当作是一个存档吧
先上代码:
- //checkleaks.h
- #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
- //checkleaks.cpp
- #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)
- {
- // This function is called several times for each memory leak.
- // Each time a part of the error message is supplied.
- // This holds number of subsequent detail messages after
- // a leak was reported
- const int numFollowupDebugMsgParts = 2;
- static bool ignoreMessage = false;
- static int debugMsgPartsCount = 0;
- // check if the memory leak reporting starts
- if ((strncmp(userMessage,"Detected memory leaks!/n", 10) == 0)
- || ignoreMessage)
- {
- // check if the memory leak reporting ends
- if (strncmp(userMessage,"Object dump complete./n", 10) == 0)
- {
- _CrtSetReportHook(prevHook);
- ignoreMessage = false;
- } else
- ignoreMessage = true;
- // something from our own code?
- if(strstr(userMessage, ".cpp") == NULL)
- {
- if(debugMsgPartsCount++ < numFollowupDebugMsgParts)
- // give it back to _CrtDbgReport() to be printed to the console
- return FALSE;
- else
- return TRUE; // ignore it
- } else
- {
- debugMsgPartsCount = 0;
- // give it back to _CrtDbgReport() to be printed to the console
- return FALSE;
- }
- } else
- // give it back to _CrtDbgReport() to be printed to the console
- return FALSE;
- };
- void setFilterDebugHook(void)
- {
- //change the report function to only report memory leaks from program code
- prevHook = _CrtSetReportHook(reportingHook);
- }
- #endif
- //main.cpp
- #include <windows.h>
- #include <stdio.h>
- #include "checkleaks.h"
- int main()
- {
- //一定要加上这句,而且要在DEBUG模式下才会有报告输出
- _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
- int *arr;
- arr = new int;
- return 0;
- }
程序输出:
- Detected memory leaks!
- Dumping objects ->
- e:vs2008tryctempctempmain.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