利用CRT库函数检查内存泄漏
生活随笔
收集整理的這篇文章主要介紹了
利用CRT库函数检查内存泄漏
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
條件:
1. 在Debug模式下。
2.#define _CRTDBG_MAP_ALLOC
?? #include "stdlib.h"
?? #include "crtdbg.h"
?
_CrtDumpMemoryLeaks()可以打印出目前為止沒有釋放的已申請內存。
// Necessary #define _CRTDBG_MAP_ALLOC #include "stdlib.h" #include "crtdbg.h"int main() {int* p = new int(2);// Report memory leak until now._CrtDumpMemoryLeaks();delete p;return 0; }?
上述代碼輸出如下:
Detected memory leaks!
Dumping objects ->
{53} normal block at 0x00394FC0, 4 bytes long.
Data: <??? > 02 00 00 00
Object dump complete.
其中{53}表示第53次申請的內存沒有釋放。
?
_CrtSetBreakAlloc(long n)可以在Debug時讓程序自動在第n次申請內存的代碼處停止。
// Necessary #define _CRTDBG_MAP_ALLOC #include "stdlib.h" #include "crtdbg.h"int main() {_CrtSetBreakAlloc(53);int* p = new int(2);// Report memory leak until now._CrtDumpMemoryLeaks();delete p;return 0; }?
在Debug上述代碼時,可以在程序停止處查看調用堆棧找到引起泄漏的內存分配代碼:
?
當程序有多個退出點時,可以調用Using _CrtSetDbgFlag()讓程序在結束時輸出內存泄漏信息。
// Necessary #define _CRTDBG_MAP_ALLOC #include "stdlib.h" #include "crtdbg.h"int main() {_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);int* p = new int(2);return 0; } ?轉載于:https://www.cnblogs.com/playerken/archive/2011/08/24/2152534.html
總結
以上是生活随笔為你收集整理的利用CRT库函数检查内存泄漏的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaScript实现继承机制(3)—
- 下一篇: (android 实战总结)androi