c:
1
#define
_CRTDBG_MAP_ALLOC
2
#include
<
stdlib.h
>
3
#include
<
crtdbg.h
>
4
//
以上的顺序必须严格如此
5
6
int
main() {
7
int
*
p;
8
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF
|
_CRTDBG_LEAK_CHECK_DF );
//
程序结束时自动调用_CrtDumpMemoryLeaks()
9
10
p
=
(
int
*
)malloc(
sizeof
(
int
));
11
12
//
_CrtDumpMemoryLeaks(); 设置了前面的flag,就不需要再在程序出口调用此函数
13
return
0
;
14
}
15
结果:
1
Detected memory leaks
!
2
Dumping objects
->
3
d:\documents\visual studio
2008
\projects\memory leak check\test\main.c(
10
) : {
60
} normal block at
0x004F4A10
,
4
bytes
long
.
4
Data:
<
>
CD CD CD CD
5
Object dump complete.
c++:
1
#define
_CRTDBG_MAP_ALLOC
2
#include
<
stdlib.h
>
3
#include
<
crtdbg.h
>
4
5
//
覆盖掉默认的new操作符
6
#define
DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
7
#define
new DEBUG_NEW
8
9
int
main() {
10
int
*
p;
11
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF
|
_CRTDBG_LEAK_CHECK_DF );
12
p
=
new
int
[
4
];
13
14
//
_CrtDumpMemoryLeaks();
15
return
0
;
16
}
17
结果:
1
Detected memory leaks
!
2
Dumping objects
->
3
d:\documents\visual studio
2008
\projects\memory leak check\test\main.cpp(
13
) : {
60
} normal block at
0x00504A10
,
16
bytes
long
.
4
Data:
<
>
CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD
5
Object dump complete.
mfc:
1
#ifdef _DEBUG
2
#define
new DEBUG_NEW
3
#endif
程序结束时在Output即输出内存泄漏信息。
如果需要检测某一段内存:
1
#ifdef _DEBUG
2
CMemoryState oldMemState, newMemState, diffMemState; //内存快照
3
#endif
4
5
#ifdef _DEBUG
6
oldMemState.Checkpoint();
7
#endif
8
9
//
memory operations
10
11
#ifdef _DEBUG
12
newMemState.Checkpoint();
13
if
( diffMemState.Difference( oldMemState, newMemState ) )
14
{
15
TRACE(
"
Memory leaked!\n
"
);
16
diffMemState.DumpStatistics();
17
diffMemState.DumpAllObjectsSince();
18
}
19
#endif
参考:
1. 这篇帖子解决在c++中如何显示行号,即覆盖原new操作符
http://www.gamedev.net/community/forums/topic.asp?topic_id=484434
2. MSDN: Memory Leak Detection Enabling
http://msdn.microsoft.com/en-us/library/e5ewb1h3%28VS.80%29.aspx
3. MSDN: _CRTDBG_MAP_ALLOC
http://msdn.microsoft.com/en-us/library/10t349zs.aspx
4. codeguru: Visual C++ Debugging: How to manage memory leaks?
http://www.codeguru.com/forum/showthread.php?t=312742
5. MSDN: MFC Debugging Techniques
http://msdn.microsoft.com/en-us/library/7sx52ww7%28VS.80%29.aspx
5.1. MSDN: Memory Leak Detection in MFC
http://msdn.microsoft.com/en-us/library/c99kz476%28VS.80%29.aspx
5.1.1. MSDN: Memory Allocation Tracking
http://msdn.microsoft.com/en-us/library/kxx6e7z6%28VS.80%29.aspx