加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 06:09:58 所属栏目:大数据 来源:网络整理
导读:在 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.Clas
在 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:pathtoDemo.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测试)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读