Disclaimer: Checkleaks.h and checkleaks.cpp The code in these two files is copied online, but the original site is not found now
Therefore, this article is not completely original, hehe.
Just think of it as an archive.
First on the code:
[CPP]View Plaincopyprint?
- 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 was 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", ten) = = 0)
- || Ignoremessage)
- {
- //Check if the memory leak reporting ends
- if (strncmp (usermessage,"Object dump complete./n", ten) = = 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 being printed to the console
- return FALSE;
- Else
- return TRUE; //Ignore it
- } Else
- {
- Debugmsgpartscount = 0;
- //Give it back to _CrtDbgReport () to being printed to the console
- return FALSE;
- }
- } Else
- //Give it back to _CrtDbgReport () to being printed to the console
- return FALSE;
- };
- void Setfilterdebughook (void)
- {
- //change the "report function" to "Report memory leaks " from program code
- Prevhook = _CrtSetReportHook (Reportinghook);
- }
- #endif
- Main.cpp
- #include <windows.h>
- #include <stdio.h>
- #include "Checkleaks.h"
- int main ()
- {
- //Be sure to add this sentence and have the report output in debug mode
- _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _crtdbg_leak_check_df);
- int *arr;
- arr = new int;
- return 0;
- }
Program output:
[CPP]View Plaincopyprint?
- Detected memory leaks!
- Dumping objects
- E:\vs2008\Try\ctemp\ctemp\main.cpp (9): {$} client block at 0x00503de8, subtype 0, 4 bytes long.
- Data: < > CD CD CD
- Object dump complete.
- The program ' [3348] ctemp.exe:Native ' have exited with code 0 (0x0).
http://blog.csdn.net/small_qch/article/details/6856445
Detecting memory leaks in VCs