delphi – 如何检测Free Pascal / Lazarus中的内存泄漏?

前端之家收集整理的这篇文章主要介绍了delphi – 如何检测Free Pascal / Lazarus中的内存泄漏?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Delphi,我通常写一个简单的泄漏测试,如下所示:
program MemLeak;

{$APPTYPE CONSOLE}

uses
    SysUtils;

procedure Leak;
begin
    { Put leaking code here. }
end;

begin
    ReportMemoryLeaksOnShutdown:= True;
    try
        Leak;
    except
        on E: Exception do
            Writeln(E.ClassName,': ',E.Message);
    end;
end.

如何在Free Pascal/Lazarus中检测内存泄漏?

解决方法

免费Pascal有类似的功能.在程序结束时,调用DumpHeap,或在Lazarus项目设置中启用heaptrc选项.输出文件可以使用SetHeapTraceOutput方法进行设置.这两种方法都在单位heaptrc中,它必须是项目中的第一个(从开始捕获分配).

更多信息:

> http://www.freepascal.org/docs-html/rtl/heaptrc/usage.html
> http://www.freepascal.org/docs-html/rtl/heaptrc/environment.html

泄漏可视化:Lazarus软件包“LeakView”在树视图中显示堆跟踪输出文件内容.它被包含在默认安装中,并且在重建IDE之后可用. (尚未测试)

// By default information is written to standard output,// this function allows you to redirect the information to a file
  SetHeapTraceOutput('heaptrace.log');

  // normally the heap dump will be written automatically at the end,// but can also be written on demand any time   
  DumpHeap;

输出如下:

C:\path\to\Demo.exe 
Heap dump by heaptrc unit
244 memory blocks allocated : 8305/9080
241 memory blocks freed     : 8237/9000
3 unfreed memory blocks : 68
True heap size : 458752
True free heap : 458288
Should be : 458480
Call trace for block $0010CE58 size 28
  $0044ACCB  TIDTHREADSAFE__CREATE,line 226 of C:/path/to/indy-10.5.8.tiburon/Lib/Core/IdThreadSafe.pas
  $00444245  IDTHREAD_init,line 641 of C:/path/to/indy-10.5.8.tiburon/Lib/Core/IdThread.pas
  $00409D74
  $0040E1A1
  ...

(用Free Pascal 2.6.0测试)

猜你在找的Delphi相关文章