Re: Freeing the result of a Delphi function


[ DelphiLand FAQ ]

Posted by webmaster Guido on July 26, 2004 at 20:24:17:

In Reply to: Freeing a result posted by Joey on July 22, 2004 at 00:34:48:

: I was just wondering if a function freeded its result after use no matter the type. I have a function with TStringList as a result and i have to use:
: Result := TStringList.Create;
: But i can't use .Free at the end or i get no result. I was just wondering if delphi did it for you :P if not how could i get round it so i don't churn-up memory??
------------------------

Delphi does not automatically Free (destroy) *objects* that you created in your code. If you create an object, you have to Free it yourself, such as: TStringList, TList, and so on.

An example. Let's say that function MakeList creates a TStringList object, and MakeList is called from Button1OnClick:

Function MakeList(A, B: string): TStringList;
begin
  Result := TStringList.Create;
  Result.Add(A);
  Result.Add(B);
end;
Procedure TForm1.Button1OnClick(Sender: TObject);
var
  S1, S2: string
  SList: TStringList;
begin
  S1 := 'String 1';
  S2 := 'String 2';
  SList := MakeList(S1, S2);
  // Do something with SList,
  // for example: save it to a file
  SList.SaveToFile('C:\Test\Test.txt');
  // Finally, free SList
  SList.Free;
end;

S1 and S2 are cleaned up automatically when Button1OnClick ends, but SList has to be destroyed by you, the programmer. And, as you wrote, you can't destroy it in the function MakeList, or otherwise you have nothing left as a Return value ;-) so, free it in the calling routine.

Anyway, I think it's safer and also easier to debug, if you both *create* and *free* the object in the calling routine Button1OnClick, and fill it in a procedure AddToList. Example:

// SL was created in the calling routine
procedure AddToList(SL: TStringList; A, B: string);
begin
  SL.Add(A);
  SL.Add(B);
end;
Procedure TForm1.Button1OnClick(Sender: TObject);
var
  S1, S2: string
  SList: TStringList;
begin
  S1 := 'String 1';
  S2 := 'String 2';
  SList := TStringList.Create;          // create in calling routine
  SList := AddToList(SList, S1, S2);
  SList.SaveToFile('C:\Test\Test.txt'); // ...destroy in calling routine
  SList.Free;
end;
webmaster Guido

Related Articles and Replies


[ DelphiLand FAQ ]