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

Why Windbg cannot see memory leaks created in delphi?

正如题主所说,为什么windbg看不到在delphi中分配的任何内存?例如 !heap -s 什么也没给出,而有意创建的 10MB 内存泄漏只是为了测试目的。

如何delphi分配内存而不从堆中取出?

!heap 使用通过调用 HeapAllocHeapReAlloc 等分配的内存。Delphi 的默认内存管理器使用 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.

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