为什么Windbg看不到在delphi中创建的内存泄漏?

moo*_*ose 1 delphi debugging windbg

正如主题所说,为什么windbg看不到在delphi中分配的任何内存?例如!heap -s什么都没有,而有意创建的10MB内存泄漏仅用于测试目的.

delphi如何在不从堆中获取内存的情况下分配内存?

Dav*_*nan 8

!heap通过调用分配的内存工作HeapAlloc,HeapReAlloc等德尔福的默认内存管理器使用VirtualAlloc,然后实现它自己的子分配器.因此,Delphi的内存管理器正在执行各种任务HeapAlloc.这意味着由Delphi的默认内存管理器分配的内存是不可见的!heap.

如果你真的想使用WinDbg !heap然后你可以用一个内置的Delphi内存管理器替换它HeapAlloc.也许这符合您的调试要求.我不太清楚是什么驱使你去WinDbg和!heap.

或者,如果您希望使用本机Delphi方法来查找泄漏,可以使用FastMM4(完整版本而不是Delphi内置版本)或madExcept 4等工具.

作为一个简单的内存管理器替换的演示,HeapAlloc我提供了这个单元:

unit HeapAllocMM;

interface

implementation

uses
  Windows;

function GetMem(Size: NativeInt): Pointer;
begin
  Result := HeapAlloc(0, 0, size);
end;

function FreeMem(P: Pointer): Integer;
begin
  HeapFree(0, 0, P);
  Result := 0;
end;

function ReallocMem(P: Pointer; Size: NativeInt): Pointer;
begin
  Result := HeapReAlloc(0, 0, P, Size);
end;

function AllocMem(Size: NativeInt): Pointer;
begin
  Result := GetMem(Size);
  if Assigned(Result) then begin
    FillChar(Result^, Size, 0);
  end;
end;

function RegisterUnregisterExpectedMemoryLeak(P: Pointer): Boolean;
begin
  Result := False;
end;

const
  MemoryManager: TMemoryManagerEx = (
    GetMem: GetMem;
    FreeMem: FreeMem;
    ReallocMem: ReallocMem;
    AllocMem: AllocMem;
    RegisterExpectedMemoryLeak: RegisterUnregisterExpectedMemoryLeak;
    UnregisterExpectedMemoryLeak: RegisterUnregisterExpectedMemoryLeak
  );

initialization
  SetMemoryManager(MemoryManager);

end.
Run Code Online (Sandbox Code Playgroud)

将其列为.dpr文件的uses子句中的第一个单元.完成此操作后,WinDbg !heap应该开始看到您的Delphi堆分配.

  • 用于调试目的的'HeapAlloc` Delphi MM可以在5分钟内完成.FastMM和madExcept都是非常好的泄漏检测工具.FastMM不会花一分钱.madExcept便宜且质量上乘. (4认同)