How to detect memory leaks in Free Pascal/Lazarus?

kludg picture kludg · Oct 14, 2012 · Viewed 7k times · Source

In Delphi, I usually write a simple leak test like this:

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.

How do I detect memory leaks in Free Pascal/Lazarus?

Answer

mjn picture mjn · Oct 14, 2012

Free Pascal has a similar feature. At the end of the program, call DumpHeap, or enable the heaptrc option in the Lazarus project settings. The output file can be set with the SetHeapTraceOutput method. Both methods are in the unit heaptrc which must be the first in the project (to capture allocations from start).

More information:

Leak visualization: the Lazarus package "LeakView" presents the content of a heap trace output file in a tree view. It is included in the default installation and available after a rebuild of the IDE. (not yet tested by me)

  // 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;

The output looks like:

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
  ...

(tested with Free Pascal 2.6.0)