Home:ALL Converter>ZDecompressStream() causes memory leak

ZDecompressStream() causes memory leak

Ask Time:2013-11-08T14:31:40         Author:rsrx

Json Formatter

I've been using ZLib functions to compress/uncompress streams in memory. In case when I try to uncompress invalid stream, it leaks memory. The following code would leak memory:

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.

I try to decompress empty TMemoryStream here and at the end of execution it shows that memory leak happened. Testing on Delphi XE2.

Any ideas how to prevent this leak to happen, because in real world there would be a chance for my application to try to decompress invalid stream and leak the memory there.

QC: http://qc.embarcadero.com/wc/qcmain.aspx?d=120329 - claimed fixed starting with XE6

Author:rsrx,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/19852941/zdecompressstream-causes-memory-leak
yy