Wolfgang Bures
Wolfgang Bures

Reputation: 717

Free TStringlist as function result?

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?

Upvotes: 3

Views: 1308

Answers (1)

Dalija Prasnikar
Dalija Prasnikar

Reputation: 28539

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.

Upvotes: 4

Related Questions