[fpc-pascal] Basic question about TStringList

Crause, Christo (JC) christo.crause at sasol.com
Fri Mar 28 07:45:23 CET 2008


> From: g.marcou at chimie.u-strasbg.fr

> As a consequence I have another question. Suppose I have a function  
> that returns a TStringList:
> 
> Myfunction(): TStringList;
> 
> I must have inside a line like:
> 
> Result:=TStringList.Create;
> 
> Let A be a TStringList, I have two ways to catch the result 
> of my function:
> 
> A:=Myfunction();
> 
> or
> 
> A.Assign(Myfunction());
> 
> In the first case, if do A.Free, I release the memory 
> allocated by the  
> function. What's arriving in the second case? I can do A.Free, but  
> does that action will also release the memory allocated by 
> the function?
> 
> By the way, do you have some tricks to detect this kind of error?

This consequence of returning references to newly created objects is a
very subtle one and I have seen some spectacular memory leaks caused by
this practice.  My programming convention is to try to always call
.Create
and .Free in the same context if possible i.e.

procedure Myfunction(const ASL: TStringList);
begin
// add stuff to ASL
end;

And in code using this function:

SL := TStringList.Create;
Myfunction(SL);
// do stuff
SL.Free;

Not quite bullet proof yet, since one can call Myfunction without
actually
instantiating SL, but at least that should give you a runtime error that
should be easy to trace.

Regards
Christo Crause
----------------------------------------------------------------------------
NOTICE: Please note that this eMail, and the contents thereof, 
is subject to the standard Sasol eMail legal notice which may be found at: 
http://www.sasol.com/legalnotices                                                                                                          

If you cannot access the legal notice through the URL attached and you wish 
to receive a copy thereof please send an eMail to 
legalnotice at sasol.com
----------------------------------------------------------------------------



More information about the fpc-pascal mailing list