使用方法

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
 
// MFCLeakerTest.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "MFCLeakerTest.h"
#include "MFCLeakerTestDlg.h"
#include "MemLeakDetect.h"

// CMFCLeakerTestApp

BEGIN_MESSAGE_MAP(CMFCLeakerTestApp, CWinApp)
    ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()

// CMFCLeakerTestApp construction

CMFCLeakerTestApp::CMFCLeakerTestApp()
{
    CLeakMemory *pMem;

pMem = new CLeakMemory();

// TODO: add construction code here,
    // Place all significant initialization in InitInstance
}

// Detect Memory Leaks
#ifdef _DEBUG
CMemLeakDetect memLeakDetect;
#endif

// The one and only CMFCLeakerTestApp object

CMFCLeakerTestApp theApp;

// CMFCLeakerTestApp initialization

BOOL CMFCLeakerTestApp::InitInstance()
{
    // InitCommonControls() is required on Windows XP if an application
    // manifest specifies use of ComCtl32.dll version 6 or later to enable
    // visual styles.  Otherwise, any window creation will fail.
    InitCommonControls();

CWinApp::InitInstance();

AfxEnableControlContainer();

...

}

 C++ Code :*.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
 
/*************************************************************
 Author     : David A. Jones
 File Name  : MemLeakDetect.h
 Date       : July 30, 2004
 Synopsis   :        
            A trace memory feature for source code to trace and
            find memory related bugs. 
 Future     :
                1) Memory corruption
                2) Freeing memory without allocating
                3) Freeing memory twice
                4) Not Freeing memory at all
                5) over running memory boundardies
        July 2009: Tim Stevens (UNICODE/ANSI 32 bit only, more secure CRT with VS 2008).
        Feb  2011: Doug Rogers, Igor Jambrek, OfekSH & tim. (Compiles as 64 & 32 bit).
        Based on http://www.codeproject.com/cpp/MemLeakDetect.asp
****************************************************************/
/*
Compiles clean in Visual Studio 2008 SP1 in 32 & 64 UNICODE and MultiByte builds.
By default, disabled in Release mode, since it relies on the Debug MS 
Runtime DLLs, the licence terms of which only allow redistribution in 
Release mode. However, if you do want to use it in Release mode, then comment out the
"#ifdef _DEBUG" lines that guard the complete MemLeakDetect.h & .cpp files, 
and link against the Debug runtimes
(e.g. /MTd instead of /MT) in Release mode.
Please don't use precompiled headers for this file.
To catch most malloc/free or new/delete leaks, simply add this 
block of code (& #define MEMORY_LEAK_CHECK)
at the application level:
#ifdef _DEBUG
    #ifdef MEMORY_LEAK_CHECK
        #include "MemLeakDetect.h"
        static CMemLeakDetect memLeakDetect;
    #endif
#endif
A typical leak might be:
    int *pfoo = new int[1000];
Then forgetting to do
    delete [] pfoo;
Then when running under a debugger, if there is a leak, you'll get this kind of 
output in the Output pane.
You'll also get files with names like "mldetector-(AppName.exe)_Feb16-2011__21-53-43.log"
written to your %TEMP% directory:
Memory Leak(1)------------------->
Memory Leak <0xBC> bytes(86) occurance(0)
c:\code\ta2svn\sandbox\pjh\software\common\memleakdetect.cpp(201): 0x0044B7C3->CMemLeakDetect::addMemoryTrace()
c:\code\ta2svn\sandbox\pjh\software\common\memleakdetect.cpp(140): 0x0044B4B2->catchMemoryAllocHook()
0x0012D874->_malloc_dbg()
0x0012D874->_malloc_dbg()
0x0012D874->_malloc_dbg()
0x0012D874->malloc()
0x0012D874->??2@YAPAXI@Z()
f:\dd\vctools\crt_bld\self_x86\crt\src\newaop.cpp(7): 0x004B4D1E->operator new[]()
c:\code\ta2svn\sandbox\pjh\software\hw_app\hw_app.cpp(145): 0x00442276->wmain()
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c(579): 0x004B56C8->__tmainCRTStartup()
f:\dd\vctools\crt_bld\self_x86\crt\src\crtexe.c(399): 0x004B550F->wmainCRTStartup()
0x0012D874->RegisterWaitForInputIdle()
-----------------------------------------------------------
Total 1 Memory Leaks: 86 bytes Total Alocations 276
You can then double-click in the Output pane on the leak ((145) in the example above) and be taken to the source line
which caused the leak.
*/
#if !defined(MEMLEAKDETECT_H)
#define MEMLEAKDETECT_H
#ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <map>
#define _CRTBLD
#include <windows.h>
#include <..\crt\src\dbgint.h>
#include <imagehlp.h>
#include <crtdbg.h>
#pragma comment( lib, "imagehlp.lib" )
using namespace std;
// if you want to use the custom stackwalker otherwise
// comment this line out

//

#define MLD_TRACEINFO_EMPTY         _T("")
#define MLD_TRACEINFO_NOSYMBOL      _T("?(?)")
#ifdef  MLD_CUSTOMSTACKWALK
#define MLD_STACKWALKER             symStackTrace2
#else
#define MLD_STACKWALKER             symStackTrace
#endif
#define AfxTrace MyTrace
#ifndef _WIN64
typedef DWORD ADDR;
typedef PIMAGEHLP_SYMBOL IMAGE_SYM;
typedef IMAGEHLP_LINE IMAGE_LN;
#else
typedef DWORD64 ADDR;
typedef PIMAGEHLP_SYMBOL64 IMAGE_SYM;
typedef IMAGEHLP_LINE64 IMAGE_LN;
#endif
class CMemLeakDetect
{
    public:
        typedef struct  {
                ADDRESS             addrPC;
                ADDRESS             addrFrame;
            
        } STACKFRAMEENTRY;
        typedef struct tagAllocBlockInfo
        {
            //  Added constructor to zero memory - thanks to bugfix from OfekSH.
                tagAllocBlockInfo() { ZeroMemory(traceinfo, sizeof(traceinfo) ); }
                void*               address; 
                size_t              size;
                TCHAR               fileName[MLD_MAX_NAME_LENGTH];
                DWORD               lineNumber;
                DWORD               occurance;
                STACKFRAMEENTRY     traceinfo[MLD_MAX_TRACEINFO];
        } AllocBlockInfo;
        //typedef int POSITION;
        typedef map<lpvoid,>                KEYMAP;
        typedef map<lpvoid,>::iterator  POSITION;
        typedef pair<lpvoid,>           KEYVALUE;
        class CMapMem
        {
            public:
                KEYMAP          m_Map;
                POSITION        m_Pos;
                inline BOOL Lookup(LPVOID pAddr,  AllocBlockInfo& aInfo) { 
                    m_Pos = m_Map.find(pAddr);
                    //
                    if (m_Pos == m_Map.end())
                    {
                        return FALSE;
                    }
                    //
                    pAddr = m_Pos->first;
                    aInfo = m_Pos->second;
                    return TRUE;
                };
                inline POSITION end() { 
                    return m_Map.end(); 
                };
                inline void RemoveKey(LPVOID pAddr) { 
                    
                    m_Map.erase(pAddr);
                };
                inline void RemoveAll() {
                    m_Map.clear();
                };
                void SetAt(LPVOID pAddr, AllocBlockInfo& aInfo) {
                    m_Map[pAddr] = aInfo;
                };
                inline POSITION GetStartPosition() { 
                    POSITION pos = m_Map.begin(); 
                    return pos;
                };
                inline void GetNextAssoc(POSITION& pos, LPVOID& rAddr, AllocBlockInfo& aInfo) {
                    rAddr = pos->first;
                    aInfo = pos->second;
                    pos++;
                };
                void InitHashTable(int preAllocEntries, BOOL flag)  {
                     preAllocEntries    = NULL;
                     flag               = NULL;
                };
        };
        CMemLeakDetect();
        ~CMemLeakDetect();
        void Init();
        void End();
        void addMemoryTrace(void* addr,  size_t asize,  TCHAR *fname, DWORD lnum);
        void redoMemoryTrace(void* addr,  void* oldaddr, size_t asize,  TCHAR *fname, DWORD lnum);
        void removeMemoryTrace(void* addr, void* realdataptr);
        void cleanupMemoryTrace();
        void dumpMemoryTrace();
        //
        //CMap<lpvoid,> m_AllocatedMemoryList;
        CMapMem          m_AllocatedMemoryList;
    DWORD memoccurance;
    bool  isLocked;
    //
    private:
        typedef USHORT (WINAPI *CaptureStackBackTraceType)(__in ULONG, __in ULONG, __out PVOID*, __out_opt PULONG);
        HMODULE m_k32;
        CaptureStackBackTraceType m_func;
        BOOL initSymInfo(TCHAR* lpUserPath);
        BOOL cleanupSymInfo();
        void symbolPaths( TCHAR* lpszSymbolPaths);
        void symStackTrace(STACKFRAMEENTRY* pStacktrace);
        void symStackTrace2(STACKFRAMEENTRY* pStacktrace);
        BOOL symFunctionInfoFromAddresses(ADDR fnAddress, ADDR stackAddress, TCHAR *lpszSymbol, UINT BufSizeTCHARs);
        BOOL symSourceInfoFromAddress(ADDR address, TCHAR* lpszSourceInfo);
        BOOL symModuleNameFromAddress(ADDR address, TCHAR* lpszModule);
        HANDLE              m_hProcess;
        PIMAGEHLP_SYMBOL    m_pSymbol;
        DWORD               m_dwsymBufSize;
};
#endif
#endif

 C++ Code : *.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
 
/*************************************************************
 Author     : David A. Jones
 File Name  : MemLeakDetect.h
 Date       : July 30, 2004
 Synopsis        
            A trace memory feature for source code to trace and
            find memory related bugs.

****************************************************************/
// See MemLeakDetect.h for full history.
// Based on http://www.codeproject.com/cpp/MemLeakDetect.asp
#ifdef _DEBUG
#include <tchar.h>
#include "MemLeakDetect.h"
#include <fstream>
#include <time.h>
#include <psapi.h>                  // Only needed for GetModuleBaseName().
#pragma comment(lib, "Psapi.lib")   // Only needed for GetModuleBaseName().
//#pragma warning(disable:4312) // 'type cast' : conversion from 'long' to 'void *' of greater size
//#pragma warning(disable:4313)
//#pragma warning(disable:4267)
)   // Unreferenced formal parameter.
static CMemLeakDetect*  g_pMemTrace         = NULL;
static _CRT_ALLOC_HOOK  pfnOldCrtAllocHook  = NULL;
static int catchMemoryAllocHook(int allocType, 
                         void   *userData, 
                         size_t size, 
                         int    blockType, 
                         long   requestNumber, 
          const unsigned char   *filename, // Can't be UNICODE
                         int    lineNumber) ;
static int MyTrace(LPCTSTR lpszFormat, ...);

static void DeleteOldTempFiles(const TCHAR dir[], const TCHAR type[], int DaysAge);

static int MyTrace(LPCTSTR lpszFormat, ...)
{
    va_list args;
    va_start( args, lpszFormat);
#ifndef UNICODE
    ];
    vsprintf_s( buffer, lpszFormat, args );
    return _CrtDbgReport(_CRT_WARN,NULL,NULL,NULL,buffer);
#else
    TCHAR buffer[];
    vswprintf_s( buffer, lpszFormat, args );
    ] ;
    WideCharToMultiByte(CP_ACP, ,
        fmtbuf, , NULL, NULL ) ;
    return _CrtDbgReport(_CRT_WARN,NULL,NULL,NULL,fmtbuf);
#endif
}
static int catchMemoryAllocHook(int allocType, 
                         void   *userData, 
                         size_t size, 
                         int    blockType, 
                         long   requestNumber, 
          const unsigned char   *filename,  // Can't be UNICODE
                         int    lineNumber)
{
    _CrtMemBlockHeader *pCrtHead;
    long prevRequestNumber;
#ifdef UNICODE
    ] ;
    Wname[] = L'\0' ;
#endif
    // internal C library internal allocations
    if ( blockType == _CRT_BLOCK )
    {
        return( TRUE );
    }
    // check if someone has turned off mem tracing
) && 
        (( allocType            == _HOOK_ALLOC)     || 
            ( allocType         == _HOOK_REALLOC)))
    {
        if (pfnOldCrtAllocHook)
        {
            pfnOldCrtAllocHook(allocType, userData, size, blockType, requestNumber, filename, lineNumber);
        }
        return TRUE;
    }
    // protect if mem trace is not initialized
    if (g_pMemTrace == NULL)
    {
        if (pfnOldCrtAllocHook)
        {
            pfnOldCrtAllocHook(allocType, userData, size, blockType, requestNumber, filename, lineNumber);
        }
        return TRUE;
    }
    // protect internal mem trace allocs
    if (g_pMemTrace->isLocked)
    {
        if (pfnOldCrtAllocHook)
        {
            pfnOldCrtAllocHook(allocType, userData, size, blockType, requestNumber, filename, lineNumber);
        }
        return( TRUE);
    }
    // lock the function
    g_pMemTrace->isLocked = true;
    //
#ifdef UNICODE
    int len ;
    if (NULL != filename)
    {
        len = ( ;
        MultiByteToWideChar(CP_ACP, , (char *)filename, len, Wname, len) ;
    }
    else
        len =  ;
#else
    #define Wname (char*)filename
#endif
    if (allocType == _HOOK_ALLOC)
    {
        g_pMemTrace->addMemoryTrace((void *) requestNumber, size, Wname, lineNumber);
    }
    else
    if (allocType == _HOOK_REALLOC)
    {
        if (_CrtIsValidHeapPointer(userData))
        {
            pCrtHead = pHdr(userData);
            prevRequestNumber = pCrtHead->lRequest;
            //
            if (pCrtHead->nBlockUse == _IGNORE_BLOCK)
            {
                if (pfnOldCrtAllocHook)
                {
                    pfnOldCrtAllocHook(allocType, userData, size, blockType, requestNumber, filename, lineNumber);
                }
                goto END;
            }
            g_pMemTrace->redoMemoryTrace((void *) requestNumber, (void *) prevRequestNumber, size, Wname, lineNumber);
        }
    }
    else
    if (allocType == _HOOK_FREE)
    {
        if (_CrtIsValidHeapPointer(userData))
        {
            pCrtHead = pHdr(userData);
            requestNumber = pCrtHead->lRequest;
            //
            if (pCrtHead->nBlockUse == _IGNORE_BLOCK)
            {
                if (pfnOldCrtAllocHook)
                {
                    pfnOldCrtAllocHook(allocType, userData, size, blockType, requestNumber, filename, lineNumber);
                }
                goto END;
            }
            g_pMemTrace->removeMemoryTrace((void *) requestNumber, userData);
        }
    }
END:
    // unlock the function
    g_pMemTrace->isLocked = false;
    return TRUE;
}
void CMemLeakDetect::addMemoryTrace(void* addr,  size_t asize,  TCHAR *fname, DWORD lnum)
{
    AllocBlockInfo ainfo;
    //
    if (m_AllocatedMemoryList.Lookup(addr, ainfo))
    {
        // already allocated
        AfxTrace(_T("ERROR!CMemLeakDetect::addMemoryTrace() Address(0x%p) already allocated\n"), addr);
        return;
    }
    //
    ainfo.address       = addr;
    ainfo.lineNumber    = lnum;
    ainfo.size          = asize;
    ainfo.occurance     = memoccurance++;
    MLD_STACKWALKER(&ainfo.traceinfo[]);
    //
    if (fname)
        _tcsncpy_s(&ainfo.fileName[], MLD_MAX_NAME_LENGTH, fname, MLD_MAX_NAME_LENGTH);
    else
      ainfo.fileName[;
    //
    m_AllocatedMemoryList.SetAt(addr, ainfo);
};
void CMemLeakDetect::redoMemoryTrace(void* addr,  void* oldaddr, size_t asize,  TCHAR *fname, DWORD lnum)
{
    AllocBlockInfo ainfo;
    if (m_AllocatedMemoryList.Lookup(oldaddr,(AllocBlockInfo &) ainfo))
    {
        m_AllocatedMemoryList.RemoveKey(oldaddr);
    }
    else
    {
        AfxTrace(_T("ERROR!CMemLeakDetect::redoMemoryTrace() didnt find Address(0x%08X) to free\n"), oldaddr);
    }
    //
    ainfo.address       = addr;
    ainfo.lineNumber    = lnum;
    ainfo.size          = asize;
    ainfo.occurance     = memoccurance++;
    MLD_STACKWALKER(&ainfo.traceinfo[]);
    //
    if (fname)
        _tcsncpy_s(&ainfo.fileName[], MLD_MAX_NAME_LENGTH, fname, MLD_MAX_NAME_LENGTH);
    else
      ainfo.fileName[;
    m_AllocatedMemoryList.SetAt(addr, ainfo);
};
void CMemLeakDetect::removeMemoryTrace(void* addr, void* realdataptr)
{
    AllocBlockInfo ainfo;
    //
    if (m_AllocatedMemoryList.Lookup(addr,(AllocBlockInfo &) ainfo))
    {
        m_AllocatedMemoryList.RemoveKey(addr);
    }
    else
    {
       //freeing unallocated memory
        AfxTrace(_T("ERROR!CMemLeakDetect::removeMemoryTrace() didnt find Address(0x%08X) to free\n"), addr);
    }
};
void CMemLeakDetect::cleanupMemoryTrace()
{
    m_AllocatedMemoryList.RemoveAll();
};
void CMemLeakDetect::dumpMemoryTrace()
{
    POSITION            pos;
    LPVOID              addr;
    AllocBlockInfo      ainfo;
    TCHAR               buf[MLD_MAX_NAME_LENGTH];
    TCHAR               fileName[MLD_MAX_NAME_LENGTH];
    TCHAR               symInfo[MLD_MAX_NAME_LENGTH];
    TCHAR               srcInfo[MLD_MAX_NAME_LENGTH];
    size_t              totalSize                       = ;
    ;
    STACKFRAMEENTRY*    p                               = ;
    ofstream myfile;
#ifdef UNICODE
        ] ;
#endif
    struct tm timeinfo;
    __time64_t long_time;
    _time64(&long_time);
    // Convert to local time.
    _localtime64_s(&timeinfo, &long_time);
    TCHAR TempDir[MAX_PATH];
    TCHAR ProcName[MAX_PATH];
    GetTempPath(MAX_PATH, TempDir);
    ProcName[] = _T('\0');
    GetModuleBaseName(GetCurrentProcess(), NULL, ProcName, sizeof(ProcName)/sizeof(TCHAR));
    _stprintf_s(fileName, MLD_MAX_NAME_LENGTH, _T("%smldetector-(%s)_"), TempDir, ProcName); 
    _tcsftime(buf,MLD_MAX_NAME_LENGTH, _T("%b%d-%Y__%H-%M-%S.log"),&timeinfo);

_tcscat_s(fileName,MLD_MAX_NAME_LENGTH, buf);

myfile.open (fileName);

DeleteOldTempFiles(TempDir, _T();
    //
    _tcscpy_s(symInfo, MLD_MAX_NAME_LENGTH, MLD_TRACEINFO_NOSYMBOL);
    _tcscpy_s(srcInfo, MLD_MAX_NAME_LENGTH, MLD_TRACEINFO_NOSYMBOL);
    //
    pos = m_AllocatedMemoryList.GetStartPosition();
    //
    while(pos != m_AllocatedMemoryList.end())
    {
        numLeaks++;
        _stprintf_s(buf, MLD_MAX_NAME_LENGTH, _T("Memory Leak(%d)------------------->\n"), numLeaks);
        AfxTrace(buf);
#ifdef UNICODE
        WideCharToMultiByte( CP_ACP, , NULL, NULL );
        myfile << dest;
#else
        myfile << buf;
#endif
        //
        m_AllocatedMemoryList.GetNextAssoc(pos, (LPVOID &) addr, (AllocBlockInfo&) ainfo);
        ] != NULL)
        {
            _stprintf_s(buf, MLD_MAX_NAME_LENGTH, _T("Memory Leak <0x%p> bytes(%d) occurance(%d) %s(%d)\n"), 
                    ainfo.address, ainfo.size, ainfo.occurance, ainfo.fileName, ainfo.lineNumber);
        }
        else
        {
            _stprintf_s(buf, MLD_MAX_NAME_LENGTH, _T("Memory Leak <0x%p> bytes(%d) occurance(%d)\n"), 
                    ainfo.address, ainfo.size, ainfo.occurance);
        }
        //
        AfxTrace(buf);
#ifdef UNICODE
        WideCharToMultiByte( CP_ACP, , NULL, NULL );
        myfile << dest;
#else
        myfile << buf;
#endif
        //
];
        ].addrPC.Offset)
        {
            symFunctionInfoFromAddresses( p[].addrFrame.Offset, symInfo, MLD_MAX_NAME_LENGTH);
            symSourceInfoFromAddress(     p[].addrPC.Offset, srcInfo );
            _stprintf_s(buf, MLD_MAX_NAME_LENGTH, _T("%s->%s()\n"), srcInfo, symInfo);
            AfxTrace(_T("%s->%s()\n"), srcInfo, symInfo);
#ifdef UNICODE
        WideCharToMultiByte( CP_ACP, , NULL, NULL );
        myfile << dest;
#else
        myfile << buf;
#endif
            p++;
        }
        totalSize += ainfo.size;
    }
    _stprintf_s(buf, MLD_MAX_NAME_LENGTH, _T("\n-----------------------------------------------------------\n"));
    AfxTrace(buf);
#ifdef UNICODE
        WideCharToMultiByte( CP_ACP, , NULL, NULL );
        myfile << dest;
#else
        myfile << buf;
#endif
    if(!totalSize) 
    {
        _stprintf_s(buf, MLD_MAX_NAME_LENGTH, _T("No Memory Leaks Detected for %d Allocations\n\n"), memoccurance);
        AfxTrace(buf);
#ifdef UNICODE
        WideCharToMultiByte( CP_ACP, , NULL, NULL );
        myfile << dest;
#else
        myfile << buf;
#endif
    }
    else
    {
        _stprintf_s(buf, MLD_MAX_NAME_LENGTH, _T("Total %d Memory Leaks: %d bytes Total Alocations %d\n\n"), numLeaks, totalSize, memoccurance);
    }
    AfxTrace(buf);
#ifdef UNICODE
    WideCharToMultiByte( CP_ACP, , NULL, NULL );
    const TCHAR *umb = _T("Unicode");
    myfile << dest;
#else
    myfile << buf;
    const TCHAR *umb = _T("Multibyte");
#endif
#ifdef _WIN64
    const TCHAR *w64 = _T("64 bit");
#else
    const TCHAR *w64 = _T("32 bit");
#endif
#ifdef NDEBUG
    const TCHAR *dbg = _T("release build.");
#else
    const TCHAR *dbg = _T("debug build.");
#endif
    _stprintf_s(TempDir, MAX_PATH, _T("%s %s %s\n"), umb, w64, dbg);
#ifdef UNICODE
    WideCharToMultiByte( CP_ACP, , NULL, NULL );
    myfile << dest;
    AfxTrace(TempDir);
#else
    myfile << TempDir;
    AfxTrace(TempDir);
#endif
    myfile.close();
}
void CMemLeakDetect::Init()
{
    m_func = (CaptureStackBackTraceType)(GetProcAddress( m_k32 = LoadLibrary(_T("kernel32.dll")), "RtlCaptureStackBackTrace"));
    m_dwsymBufSize      = (MLD_MAX_NAME_LENGTH + sizeof(PIMAGEHLP_SYMBOL));
    m_hProcess          = GetCurrentProcess();
    m_pSymbol               = (IMAGE_SYM)GlobalAlloc( GMEM_FIXED, m_dwsymBufSize);
    m_AllocatedMemoryList.InitHashTable(, TRUE);
    initSymInfo( NULL );
    isLocked                = false;
    g_pMemTrace         = this;
    pfnOldCrtAllocHook  = _CrtSetAllocHook( catchMemoryAllocHook ); 
}
void CMemLeakDetect::End()
{
    isLocked                = true;
    _CrtSetAllocHook(pfnOldCrtAllocHook);
    dumpMemoryTrace();
    cleanupMemoryTrace();
    cleanupSymInfo();
    GlobalFree(m_pSymbol);
    g_pMemTrace             = NULL;
    FreeLibrary(m_k32);
}
CMemLeakDetect::CMemLeakDetect()
{
    Init();
}
CMemLeakDetect::~CMemLeakDetect()
{
    End();
}
// PRIVATE STUFF
void CMemLeakDetect::symbolPaths( TCHAR* lpszSymbolPath)
{
    TCHAR lpszPath[MLD_MAX_NAME_LENGTH];
   // Creating the default path where the dgbhelp.dll is located
   // ".;%_NT_SYMBOL_PATH%;%_NT_ALTERNATE_SYMBOL_PATH%;%SYSTEMROOT%;%SYSTEMROOT%\System32;"
    _tcscpy_s( lpszSymbolPath, MLD_MAX_NAME_LENGTH, _T(".;..\\;..\\..\\"));
    // environment variable _NT_SYMBOL_PATH
    if ( GetEnvironmentVariable(_T("_NT_SYMBOL_PATH"), lpszPath, MLD_MAX_NAME_LENGTH ))
    {
        _tcscat_s( lpszSymbolPath, MLD_MAX_NAME_LENGTH, _T(";"));
        _tcscat_s( lpszSymbolPath, MLD_MAX_NAME_LENGTH, lpszPath );
    }
    // environment variable _NT_ALTERNATE_SYMBOL_PATH
    if ( GetEnvironmentVariable( _T("_NT_ALTERNATE_SYMBOL_PATH"), lpszPath, MLD_MAX_NAME_LENGTH ))
    {
        _tcscat_s( lpszSymbolPath, MLD_MAX_NAME_LENGTH, _T(";"));
        _tcscat_s( lpszSymbolPath, MLD_MAX_NAME_LENGTH, lpszPath );
    }
    // environment variable SYSTEMROOT
    if ( GetEnvironmentVariable( _T("SYSTEMROOT"), lpszPath, MLD_MAX_NAME_LENGTH ) )
    {
        _tcscat_s( lpszSymbolPath, MLD_MAX_NAME_LENGTH, _T(";"));
        _tcscat_s( lpszSymbolPath, MLD_MAX_NAME_LENGTH, lpszPath);
        _tcscat_s( lpszSymbolPath, MLD_MAX_NAME_LENGTH, _T(";"));
        // SYSTEMROOT\System32
        _tcscat_s( lpszSymbolPath, MLD_MAX_NAME_LENGTH, lpszPath );
        _tcscat_s( lpszSymbolPath, MLD_MAX_NAME_LENGTH, _T("\\System32"));
    }
}
BOOL CMemLeakDetect::cleanupSymInfo()
{
    return SymCleanup( GetCurrentProcess() );
}
// Initializes the symbol files
BOOL CMemLeakDetect::initSymInfo( TCHAR* lpszUserSymbolPath )
{
    TCHAR   lpszSymbolPath[MLD_MAX_NAME_LENGTH];
    DWORD   symOptions = SymGetOptions();
    symOptions |= SYMOPT_LOAD_LINES; 
    symOptions &= ~SYMOPT_UNDNAME;
    SymSetOptions( symOptions );
    // Get the search path for the symbol files
    symbolPaths( lpszSymbolPath);
    //
    if (lpszUserSymbolPath)
    {
        _tcscat_s(lpszSymbolPath, MLD_MAX_NAME_LENGTH, _T(";"));
        _tcscat_s(lpszSymbolPath, MLD_MAX_NAME_LENGTH, lpszUserSymbolPath);
    }
#ifdef UNICODE
     ;
    ] ;
    WideCharToMultiByte( CP_ACP, , dest, len, NULL, NULL );
    BOOL bret = SymInitialize( GetCurrentProcess(), dest, TRUE);
#else
    BOOL bret = SymInitialize( GetCurrentProcess(), lpszSymbolPath, TRUE) ;
#endif
    return bret;
}
/*void CMemLeakDetect::symStackTrace(STACKFRAMEENTRY* pStacktrace )
{
    STACKFRAME     callStack;
    BOOL           bResult;
    CONTEXT        context;
    HANDLE         hThread  = GetCurrentThread();
    // get the context
    memset( &context, NULL, sizeof(context) );
    context.ContextFlags = CONTEXT_FULL;
    if ( !GetThreadContext( hThread, &context ) )
    {
    //   AfxTrace("Call stack info(thread=0x%X) failed.\n", hThread );
       return;
    }
    //initialize the call stack
    memset( &callStack, NULL, sizeof(callStack) );
    callStack.AddrPC.Offset    = context.Eip;
    callStack.AddrStack.Offset = context.Esp;
    callStack.AddrFrame.Offset = context.Ebp;
    callStack.AddrPC.Mode      = AddrModeFlat;
    callStack.AddrStack.Mode   = AddrModeFlat;
    callStack.AddrFrame.Mode   = AddrModeFlat;
    //
    for( DWORD index = 0; index < MLD_MAX_TRACEINFO; index++ ) 
    {
        bResult = StackWalk(IMAGE_FILE_MACHINE_I386,
                            m_hProcess,
                            hThread,
                            &callStack,
                            NULL, 
                            NULL,
                            SymFunctionTableAccess,
                            SymGetModuleBase,
                            NULL);
        
        
        //if ( index == 0 )
         //  continue;
        if( !bResult || callStack.AddrFrame.Offset == 0 ) 
            break;
        //
        pStacktrace[0].addrPC    = callStack.AddrPC;
        pStacktrace[0].addrFrame = callStack.AddrFrame;
        pStacktrace++;
    }
    //clear the last entry
    memset(pStacktrace, NULL, sizeof(STACKFRAMEENTRY));
}*/
//
// This code is still under investigation
// I have to test this code and make sure it is compatible
// with the other stack walker!
//
void CMemLeakDetect::symStackTrace2(STACKFRAMEENTRY* pStacktrace )
{
    ;
    ADDR            block[];
    memset(block,,sizeof(block));
    USHORT frames = (m_func)(,(void**)block,NULL);
    ; i < frames ; i++)
    {
        ADDR            InstructionPtr = (ADDR)block[i];
        pStacktrace[StackIndex].addrPC.Offset   = InstructionPtr;
        pStacktrace[StackIndex].addrPC.Segment  = NULL;
        pStacktrace[StackIndex].addrPC.Mode     = AddrModeFlat;
        //
        StackIndex++;
    }
    pStacktrace[StackIndex].addrPC.Offset = ;
    pStacktrace[StackIndex].addrPC.Segment = ;
}
BOOL CMemLeakDetect::symFunctionInfoFromAddresses( ADDR fnAddress, ADDR stackAddress, TCHAR *lpszSymbol,
                                                    UINT BufSizeTCHARs)
{
    ADDR             dwDisp = ;
    ::ZeroMemory(m_pSymbol, m_dwsymBufSize );
    m_pSymbol->SizeOfStruct     = sizeof(IMAGEHLP_LINE64);
    //m_pSymbol->MaxNameLength  = DWORD64 - sizeof(IMAGEHLP_SYMBOL64);
    // Set the default to unknown
    _tcscpy_s( lpszSymbol, MLD_MAX_NAME_LENGTH, MLD_TRACEINFO_NOSYMBOL);
    // Get symbol info for IP
    if ( SymGetSymFromAddr( m_hProcess, (ADDR)fnAddress, &dwDisp, m_pSymbol ) )
    {
#ifdef UNICODE
         ;
        ] ;
        MultiByteToWideChar(CP_ACP, , m_pSymbol->Name, len, dest, len );
        _tcscpy_s(lpszSymbol, BufSizeTCHARs, dest);
#else
        _tcscpy_s(lpszSymbol, BufSizeTCHARs, m_pSymbol->Name);
#endif
        return TRUE;
    }
    //create the symbol using the address because we have no symbol
    _stprintf_s(lpszSymbol, BufSizeTCHARs, _T("0x%08X"), fnAddress);
    return FALSE;
}
BOOL CMemLeakDetect::symSourceInfoFromAddress(ADDR address, TCHAR* lpszSourceInfo)
{
    BOOL           ret = FALSE;
    IMAGE_LN  lineInfo;
    DWORD          dwDisp;
    TCHAR          lpModuleInfo[MLD_MAX_NAME_LENGTH] = MLD_TRACEINFO_EMPTY;
    _tcscpy_s( lpszSourceInfo, MLD_MAX_NAME_LENGTH, MLD_TRACEINFO_NOSYMBOL);
    memset( &lineInfo, NULL, sizeof( IMAGEHLP_LINE ) );
    lineInfo.SizeOfStruct = sizeof( IMAGEHLP_LINE );
    if ( SymGetLineFromAddr( m_hProcess, address, &dwDisp, &lineInfo ) )
    {
       // Using the "sourcefile(linenumber)" format
#ifdef UNICODE
        ] ;
         ;
        MultiByteToWideChar(CP_ACP, , (char *)lineInfo.FileName, len, dest, len) ;
        _stprintf_s(lpszSourceInfo, MLD_MAX_NAME_LENGTH, _T("%s(%d): 0x%08X"), dest, lineInfo.LineNumber, address );//  <--- Size of the char thing.
#else
        _stprintf_s(lpszSourceInfo, MLD_MAX_NAME_LENGTH, _T("%s(%d): 0x%08X"), lineInfo.FileName, lineInfo.LineNumber, address );// <--- Size of the char thing.
#endif
        ret = TRUE;
    }
    else
    {
        // Using the "modulename!address" format
        symModuleNameFromAddress( address, lpModuleInfo );
        ] == _T('\0'))
        {
            // Using the "address" format
            _stprintf_s(lpszSourceInfo,MLD_MAX_NAME_LENGTH,  _T("0x%p"), lpModuleInfo, address );   // Tim ???
        }
        else
        {
            _stprintf_s(lpszSourceInfo, MLD_MAX_NAME_LENGTH, _T("%sdll! 0x%08X"), lpModuleInfo, address );
        }
        ret = FALSE;
    }
    //
    return ret;
}
BOOL CMemLeakDetect::symModuleNameFromAddress( ADDR address, TCHAR* lpszModule )
{
    BOOL              ret = FALSE;
    IMAGEHLP_MODULE   moduleInfo;
    ::ZeroMemory( &moduleInfo, sizeof(IMAGEHLP_MODULE) );
    moduleInfo.SizeOfStruct = sizeof(IMAGEHLP_MODULE);
    if ( SymGetModuleInfo( m_hProcess, (ADDR)address, &moduleInfo ) )
    {
        // Note. IMAGEHLP_MODULE::ModuleName seems to be hardcoded as 32 char/wchar_t (VS2008).
#ifdef UNICODE
         ;
        ] ;
        WideCharToMultiByte( CP_ACP, , dest, len, NULL, NULL );
        strcpy_s(moduleInfo.ModuleName, , dest);  // bloody ANSI!
#else
        strcpy_s(moduleInfo.ModuleName, , lpszModule);
#endif
        ret = TRUE;
    }
    else
    {
        _tcscpy_s( lpszModule, MLD_MAX_NAME_LENGTH, MLD_TRACEINFO_NOSYMBOL);
    }
    
    return ret;
}
static void DeleteOldTempFiles(const TCHAR dir[], const TCHAR type[], int days)
{
    union tu
    {
        FILETIME fileTime;
        ULARGE_INTEGER ul;
    };  // Seems simplest way to do the Win32 time manipulation.
    WIN32_FIND_DATA FindFileData;
    HANDLE hFind = INVALID_HANDLE_VALUE;

TCHAR curdir[MAX_PATH];
    GetCurrentDirectory(MAX_PATH, curdir);  // Ignoring failure!
    SetCurrentDirectory(dir);

hFind = FindFirstFile(type, &FindFileData);

if (hFind != INVALID_HANDLE_VALUE)
    {
        SYSTEMTIME st;
        tu ft;

GetSystemTime(&st);
        SystemTimeToFileTime(&st, &ft.fileTime);

)
        {
            if (FILE_ATTRIBUTE_DIRECTORY != FindFileData.dwFileAttributes)
            {
                tu t;
                t.fileTime = FindFileData.ftCreationTime;

_int64 delta = (ft.ul.QuadPart - t.ul.QuadPart) / ; // Seconds.
));
                //_tprintf (TEXT("Next file name is: %s delta days %d\n"), FindFileData.cFileName, ddays);
                if (ddays >= days)
                {
                    //_tprintf (TEXT("Next file to delete is: %s delta days %d\n"), FindFileData.cFileName, ddays);
                    DeleteFile(FindFileData.cFileName);
                }
                //else
                //{
                //  _tprintf (TEXT("Skipping: %s delta days %d\n"), FindFileData.cFileName, ddays);
                //}
            }
        }
        FindClose(hFind);

}
    SetCurrentDirectory(curdir);
}
#endif

VC++为你的程序增加内存泄露检测的更多相关文章

  1. Linux下C程序内存泄露检测

    在linux下些C语言程序,最大的问题就是没有一个好的编程IDE,当然想kdevelop等工具都相当的强大,但我还是习惯使用kdevelop工具,由于没有一个习惯的编程IDE,内存检测也就成了在lin ...

  2. VC++ 启用内存泄露检测

    _CrtDumpMemoryLeaks()就是检测从程序开始到执行该函数进程的堆使用情况,通过使用_CrtDumpMemoryLeaks()我们可以进行简单的内存泄露检测. #include &quo ...

  3. Visual C++内存泄露检测—VLD工具使用说明[转]

    Visual C++内存泄露检测—VLD工具使用说明 一.        VLD工具概述 Visual Leak Detector(VLD)是一款用于Visual C++的免费的内存泄露检测工具.他的 ...

  4. Visual C++内存泄露检测—VLD工具使用说明

    一.        VLD工具概述 Visual Leak Detector(VLD)是一款用于Visual C++的免费的内存泄露检测工具.他的特点有:可以得到内存泄漏点的调用堆栈,如果可以的话,还 ...

  5. vld(Visual Leak Detector) 内存泄露检测工具

    初识Visual Leak Detector 灵活自由是C/C++语言的一大特色,而这也为C/C++程序员出了一个难题.当程序越来越复 杂时,内存的管理也会变得越加复杂,稍有不慎就会出现内存问题.内存 ...

  6. Android内存泄露---检测工具篇

    内存使用是程序开发无法回避的一个问题.如果我们毫不在意肆意使用,总有一天会为此还账,且痛不欲生...所以应当防患于未然,把内存使用细化到平时的每一行代码中. 内存使用概念较大,本篇先讲对已有app如何 ...

  7. vld,Bounds Checker,memwatch,mtrace,valgrind,debug_new几种内存泄露检测工具的比较,Valgrind Cheatsheet

    概述 内存泄漏(memory leak)指由于疏忽或错误造成程序未能释放已经不再使用的内存的情况,在大型的.复杂的应用程序中,内存泄漏是常见的问题.当以前分配的一片内存不再需要使用或无法访问时,但是却 ...

  8. 【VS开发】Visual C++内存泄露检测—VLD工具使用说明

    Visual C++内存泄露检测-VLD工具使用说明 一.        VLD工具概述 Visual Leak Detector(VLD)是一款用于Visual C++的免费的内存泄露检测工具.他的 ...

  9. Windows下C/C++内存泄露检测机制

    1.概述 在Windows下微软给我们提供了一个十分强大的C/C++运行时库,这个运行时库中包含了很多有用的功能.而众多强大功能之一就是内存泄露的检测. C/C++提供了强大的内存管理功能,不过随之而 ...

随机推荐

  1. 19-spring学习-springMVC环境配置

    新建一共环境,添加spring支持,就可以开发springMVC了. 既然是springMVC,就必须为其定义相关配置. 1,springMVC所有配置都需要在applicationContext.x ...

  2. Maven + Apache Felix + CXF + DOSGi series

    This is a blog series on how to combine Maven + Apache Felix + CXF + DOSGi. The information presente ...

  3. HttpClient + PATCH support

    From - http://compiledexperience.com/blog/posts/patch-support-in-httpclient/ public static class Htt ...

  4. 查看80port是否被占用

    windows下命令: netstat -ano|findstr "0.0:80"

  5. SuperMap iServer 9D HBase使用

    需提前将HBase进行部署,参考上篇部署文档 https://www.cnblogs.com/zhangyongli2011/p/9982143.html (转发请注明出处:http://www.cn ...

  6. PHP-权限控制类(转)

    <?php /** * 权限控制类 */ class include_purview { /** * 类的唯一实例 */ private static $instance; /** * 权限常量 ...

  7. layui数据表格自定义每页条数limit

    table.render({ elem: '#data_grid' //,width: 900 //,height: 274 ,cols: [[ //标题栏 {field: 'id', title: ...

  8. 使用kubernetes创建容器一直处于ContainerCreating状态的原因查找与解决

    运行容器的时候,发现一直处于ContainerCreating状态,悲了个催,刚入手就遇到了点麻烦,下面来讲讲如何查找问题及解决的 运行容器命令: [root@master- ~]# kubectl ...

  9. 用JIRA管理你的项目

    https://blog.csdn.net/gaowenhui2008/article/details/70241657   (一) JIRA环境搭建

  10. How to Install Xcode, Homebrew, Git, RVM, Ruby & Rails on Snow Leopard, Lion, Mountain Lion, and Mavericks

    After following many outdated and incomplete instructions for setting up a web development environme ...