Free Pascal => Beginners => Topic started by: JimD on September 13, 2018, 07:49:37 pm
Title: [SOLVED] StringList Result from Function in two Units
Post by: JimD on September 13, 2018, 07:49:37 pm
Thanks for the help - the solution is:
Return StringList from Function: Declare a StringList variable, but do not create before the Function. The Function will create the StringList. Free the StringList after use.
Return StringList from a Procedure: Declare and create the StringList variable before the Procedure. The Procedure will not create nor free this StringList. Free the StringList after use.
I want to return a StringList from a function. (I know, this is controversial, but assume it must be done)
All is good when the function is in one Unit. However, when I have the same function in two Units I get a memory leak. See my trivial example in the attached.
I'm sure I'm doing something wrong, any ideas?
I've researched and this is a good explanation of how to return StringList from a function; http://forum.lazarus.freepascal.org/index.php/topic,33204.msg214727.html#msg214727
I do not want to do the alternate recommendation from the post above: bList:=Function(const aList: TStringList): TStringList;
I do not want to create a Class, just source code I can include in other projects.
My config: Win10 Home 64-bit, Lazarus 1.8.2 with FPC 3.0.4
Title: Re: StringList Result from Function in two Units
Post by: Xor-el on September 13, 2018, 08:24:24 pm
in unit1, delete line 67 (aList.Create;), you are creating it all wrong (and even if you doing it right), you are creating the stringlist multiple times.
Title: Re: StringList Result from Function in two Units
Post by: Bart on September 13, 2018, 08:26:18 pm
When you test both units, you assign the result of the function Test/TestUnit2 to the same variable. Essentially doing:
Title: Re: StringList Result from Function in two Units
Post by: JimD on September 13, 2018, 08:39:22 pm
Thanks!
Yes, the aList.Create is a total mistake trying to post while doing my day job.
I would never do all the creates and frees as in this example for real code. However, you certainly cleared up my misunderstanding. The attached now works so I updated as solved.