klu*_*udg 12 delphi memory-leaks freepascal 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.
Run Code Online (Sandbox Code Playgroud)
如何检测Free Pascal/Lazarus中的内存泄漏?
mjn*_*mjn 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;
Run Code Online (Sandbox Code Playgroud)
输出如下:
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
...
Run Code Online (Sandbox Code Playgroud)
(使用Free Pascal 2.6.0测试)
虽然mjn是完全正确的,并且他说的是首选解决方案,但在*nix上也可以使用单元"cmem"(主程序中的第一个单元)将内存管理器切换到libc的malloc,并使用其他调试工具.
如果其他选项耗尽,那么使用valgrind这样做是值得的.请注意,要使用valgrind,您需要打开-gv.
| 归档时间: |
|
| 查看次数: |
6453 次 |
| 最近记录: |