ReportMemoryLeaksOnShutdown内存泄露检测方法

All Delphi versions since Delphi 2006 have an updated memory manager that is faster and more feature rich.

One of the nicest features of the "new" memory manager allows applications to register (and unregister) expected memory leaks, and optionally report unexpected memory leaks on program shutdown.

  

自从Delphi2006版本开始,新版的IDE加入了内存泄露报告方法。

  

When creating WIN32 applications with Delphi it is imperative to make sure that you free all the objects (memory) you create dynamically.A memory (or resource) leak occurs when the program loses the ability to free the memory it consumes.

 

内存泄露的原因主要是程序员的错误,当动态创建objects却没有在使用完毕后释放free的时候,内存泄露就发生了。

 

ReportMemoryLeaksOnShutdown

 

Memory leak detecting and reporting is set to false by default. To enable it, you need to set the global variable ReportMemoryLeaksOnShutdown to TRUE. When the applications is closed, if there are unexpected memory leaks the application will display the "Unexpected Memory Leak" dialog box.

 

打开内存泄露检测选项后,当程序运行结束且存在内存泄露的时候,程序会显示内存泄露对话框。

 

The best place for the ReportMemoryLeaksOnShutdown would be in the program's source code (dpr) file.

 

放置ReportMemoryLeaksOnShutdown的最佳位置是程序的dpr文件中,例如:

1
2
3
4
5
6
7
8
begin
<strong>ReportMemoryLeaksOnShutdown := DebugHook <> 0;</strong>
//source "by" Delphi
   Application.Initialize;
   Application.MainFormOnTaskbar := True;
   Application.CreateForm(TMainForm, MainForm) ;
   Application.Run;
end.

 

 

Note: a global variable DebugHook is used above to make sure memory leaks are displayed when the application is run in debug mode - when you fit F9 from the Delphi IDE.

 

使用全局变量DebugHook的作用是确保程序在debug模式运行时显示内存泄露报告。但是注意在正常模式运行是不会报错的。

 

 

Test Drive: Memory Leak Detection
Having ReportMemoryLeaksOnShutdown set to TRUE, add the following code in the main form's OnCreate event handler.

1
2
3
4
5
6
var
   sl : TStringList;
begin
   sl := TStringList.Create;
   sl.Add('Memory leak!') ;
end;

 

Note: If you are looking for a tool to catch your Delphi application errors such as memory corruption, memory leaks, memory allocation errors, variable initialization errors, variable definition conflicts, pointer errors ... take a look at EurekaLog

 

 

Run the application in debug mode, exit the application - you should see the memory leak dialog box.

 

 

 

上述代码就是实际测试内存泄露报告效果。

 

避免这种内存泄露的发生就是使用free方法,用nil不能释放内存。

 

 

posted on   Delphi7456  阅读(5238)  评论(1编辑  收藏  举报

编辑推荐:
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
阅读排行:
· Spring AI + Ollama 实现 deepseek-r1 的API服务和调用
· 《HelloGitHub》第 106 期
· 数据库服务器 SQL Server 版本升级公告
· 深入理解Mybatis分库分表执行原理
· 使用 Dify + LLM 构建精确任务处理应用
< 2010年11月 >
31 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 1 2 3 4
5 6 7 8 9 10 11

导航

统计

点击右上角即可分享
微信分享提示