在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中检测内存泄漏?
答案 0 :(得分:16)
Free Pascal也有类似的功能。在程序结束时,调用DumpHeap
,或在Lazarus项目设置中启用heaptrc选项。可以使用SetHeapTraceOutput
方法设置输出文件。两种方法都在单元heaptrc
中,它必须是项目中的第一个(从开始捕获分配)。
更多信息:
泄漏可视化: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测试)
答案 1 :(得分:6)
虽然mjn是完全正确的,并且他说的是首选解决方案,但在* nix上也可以使用单元“cmem”(主程序中的第一个单元)将内存管理器切换到libc的malloc,并使用其他调试工具
如果其他选项用尽,那么使用valgrind这样做是值得的。请注意,要使用valgrind,您需要打开-gv。