4

我一直在使用ZLib函数来压缩/解压缩内存中的流。如果我尝试解压缩无效流,它会泄漏内存。以下代码会泄漏内存:

uses
  Winapi.Windows, System.Classes, System.ZLib;

function DecompressStream(const AStream: TMemoryStream): Boolean;
var
  ostream: TMemoryStream;
begin
  ostream := TMemoryStream.Create;
  try
    AStream.Position := 0;

    // ISSUE: Memory leak happening here
    try
      ZDecompressStream(AStream, ostream);
    except
      Exit(FALSE);
    end;

    AStream.Clear;
    ostream.Position := 0;
    AStream.CopyFrom(ostream, ostream.Size);
    result := TRUE;
  finally
    ostream.Free;
  end;
end;

var
  s: TMemoryStream;

begin
  ReportMemoryLeaksOnShutdown := TRUE;

  s := TMemoryStream.Create;
  try
    DecompressStream(s);
  finally
    s.Free;
  end;
end.

我尝试在TMemoryStream此处解压缩为空,并在执行结束时显示发生了内存泄漏。在德尔福 XE2 上进行测试。

如何防止这种泄漏发生的任何想法,因为在现实世界中,我的应用程序将有机会尝试解压缩无效流并在那里泄漏内存。

QC: http://qc.embarcadero.com/wc/qcmain.aspx?d= 120329 - 声称从 XE6 开始已修复

4

1 回答 1

3

这是 Delphi RTL 代码中的一个错误。的实现ZDecompressStream引发异常,然后无法执行整理。让我们看一下代码:

procedure ZDecompressStream(inStream, outStream: TStream);
const
  bufferSize = 32768;
var
  zstream: TZStreamRec;
  zresult: Integer;
  inBuffer: TBytes;
  outBuffer: TBytes;
  inSize: Integer;
  outSize: Integer;
begin
  SetLength(inBuffer, BufferSize);
  SetLength(outBuffer, BufferSize);
  FillChar(zstream, SizeOf(TZStreamRec), 0);

  ZCompressCheck(InflateInit(zstream));   <--- performs heap allocation

  inSize := inStream.Read(inBuffer, bufferSize);

  while inSize > 0 do
  begin
    zstream.next_in := @inBuffer[0];
    zstream.avail_in := inSize;

    repeat
      zstream.next_out := @outBuffer[0];
      zstream.avail_out := bufferSize;

      ZCompressCheck(inflate(zstream, Z_NO_FLUSH));

      // outSize := zstream.next_out - outBuffer;
      outSize := bufferSize - zstream.avail_out;

      outStream.Write(outBuffer, outSize);
    until (zstream.avail_in = 0) and (zstream.avail_out > 0);

    inSize := inStream.Read(inBuffer, bufferSize);
  end;

  repeat
    zstream.next_out := @outBuffer[0];
    zstream.avail_out := bufferSize;

    zresult := ZCompressCheck(inflate(zstream, Z_FINISH));

    // outSize := zstream.next_out - outBuffer;
    outSize := bufferSize - zstream.avail_out;

    outStream.Write(outBuffer, outSize);
  until (zresult = Z_STREAM_END) and (zstream.avail_out > 0);

  ZCompressCheck(inflateEnd(zstream));   <--- tidy up, frees heap allocation
end;

我从我的 XE3 中获取了这个,但我相信它在所有版本中基本相同。我已经强调了这个问题。调用inflateInit从堆中分配内存。它需要与对 的调用配对inflateEnd。因为ZCompressCheck在面对错误时会引发异常,所以调用inflateEnd永远不会发生。因此代码泄漏。

对该单元的其他调用inflateInitinflateEnd该单元中的其他调用都使用 try/finally 正确保护。似乎只是在这个函数中的使用是错误的。

我的建议是Zlib用正确实施的版本替换该单元。

于 2013-11-08T09:30:38.903 回答