2

If a function I call returns a TStringList (with a TStringList.Create) and I don't assign it to a variable but use it once directly (like Data:=MyTStringFunction.Values['data'];) will I have a memory-leak or will the TStringList be freed automatically?

Dalija Prasnikar
  • 27,212
  • 44
  • 82
  • 159
Wolfgang Bures
  • 509
  • 4
  • 12
  • You could consider returning a TStringArray (= array of string) instead of a string list. That would be handled implicitly. – dummzeuch Sep 09 '20 at 13:46

1 Answers1

4

If the function creates a new string list then your code will leak.

function MyTStringFunction: TStringList;
begin
  // constructing new string list
  Result := TStringList.Create;
  ...
end;

You need to store the value of the returned list in a variable and Free it after you are done.

var
  List: TStringList;

List := MyTStringFunction;
try
  Data := List.Values['data'];
finally
  List.Free;
end;

Note: Since Delphi 10.3 Rio still uses ARC object management for its mobile compilers, if the above code runs strictly on ARC platforms (iOS, Android) then it will not leak. But if the code must run on non-ARC platforms (Windows, Linux, macOS), or is ever upgraded to Delphi 10.4, then Free needs to be called. Such code will work properly across all platforms.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Dalija Prasnikar
  • 27,212
  • 44
  • 82
  • 159