• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Fcoding_狂人
自由 编码 Fcoding
博客园    首页    新随笔    联系   管理     

C++内存泄露的检测(一)

 

一
Visual Studio 调试器和 C 运行时 (CRT) 库为我们提供了检测和识别内存泄漏的有效方法。主要使用函数:_CrtDumpMemoryLeaks();

二 实例

 1 #define _CRTDBG_MAP_ALLOC   //输出更详细的report
 2 #include <stdlib.h>
 3 #include <crtdbg.h>
 4 //以上的内容必须放在其他include的前面
 5 
 6 #include <vector>
 7 
 8 class MyClass
 9 {
10 private:
11     int *p;
12 public:
13     MyClass()
14     {
15         if(p != NULL)
16         {
17             p = new int(0);
18         }
19     }
20     ~MyClass()
21     {
22         if(p != NULL)
23         {
24             delete p;
25             p = NULL;
26         }
27     }
28 };
29 
30 int _tmain(int argc, _TCHAR* argv[])
31 {
32     int *i = NULL; // better for read
33     i = new int(0);    
34     int *&y = i; // pointer's reference
35 
36     MyClass *pMyClass = new MyClass();
37 
38     std::vector<MyClass*> myClasses;
39     myClasses.push_back(new MyClass());
40     myClasses.push_back(new MyClass());
41 
42     _CrtDumpMemoryLeaks();
43     return 0;
44 }

 

三说明
1)只对debug模有用,可以在程序运行后在vs的ide的output的最后看到泄露的检测结果。
2)可以检测系统类型,自定义类型和stl 容器。
3)#define _CRTDBG_MAP_ALLOC   //包含该宏定义输出更详细的report
      #include <stdlib.h>
      #include <crtdbg.h>
      //以上的内容必须放在其他include的前面,否则可能使上面定义的宏失效。
4)如果程序有统一的退出口,则在退出时调用_CrtDumpMemoryLeaks();
5)如果程序有多个出口,则可以在程序开始处包含下面的调用:_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );这条语句无论程序在什么地方退出都会自动调用 _CrtDumpMemoryLeaks。

四 更多(更多的API和demo的下载)
http://msdn2.microsoft.com/zh-cn/library/fxszt639(VS.80).aspx

posted @ 2012-07-04 21:37  Fcoding_狂人  阅读(606)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3