2
votes

I've written this very simple function:

function CompressStream(inpStream: TBytesStream;
                        nCmpLevel: TZCompressionLevel = zcFastest): TBytesStream;
var
  aCmpData: TBytes;
begin
  ZCompress(inpStream.Bytes, aCmpData, nCmpLevel);
  Result := TBytesStream.Create(aCmpData);
end;

Is this correct? I have a doubt about the memory persistence of the data in the local array variable aCmpData.

If we cut the row Result := TBytesStream.Create(aCmpData) we have aCmpData going out of scope when the function ends, so its associated memory is freed.

The constructor for TBytesStream takes a TBytes so I pass it my local array, this should be a "by reference" operation.

What about my data when the function ends and aCmpData goes out of scope?

1

1 Answers

3
votes

The TBytes type is a dynamic array of bytes, declared as:

TBytes = TArray<Byte>;

Such dynamic arrays are managed by the compiler, just like string variables. There is no need to release the variable explicitly, its lifetime is managed by the compiler. When there are no remaining references to the array it will be destroyed.