[fpc-pascal] string memory management

Michael Van Canneyt michael at freepascal.org
Fri Apr 19 09:02:14 CEST 2013



On Fri, 19 Apr 2013, Flávio Etrusco wrote:

> On Fri, Apr 19, 2013 at 1:36 AM, Xiangrong Fang <xrfang at gmail.com> wrote:
>> Hi All,
>>
>> I'm studying how pascal manages strings.  I wrote a simple test program:
>>
>> program stringtest;
>> {$mode objfpc}{$H+}
>> uses Classes, sysutils;
>> function test: PString;
>> var
>>   s : string;
>> begin
>>   New(Result);
>>   Result^ := FloatToStr(Random);
>> //  s := FloatToStr(Random);
>> //  Result := @s;
>> end;
>> var
>>   i : Integer;
>> begin
>>   Randomize;
>>   with TList.Create do try
>>     for i := 0 to 9 do Add(test);
>>     for i := 0 to Count - 1 do begin
>>       WriteLn(PString(Items[i])^);
>>     end;
>>   finally
>>     Free;
>>   end;
>> end.
>>
>> The program runs fine, but:
>>
>> 1. I don't know whether I have to MANUALLY free memory for these strings to
>> prevent leak?

Yes, if you work like this, you must do all that. 
You must free all pointers in the list, and the strings they point to.

But why not use TStringList ? It does all this for you.

>> 2. Does the IDE provide any facility to analyze memory usage of a program
>> and report if there are any leaks?  (There are Tools/Leak View, but I don't
>> know how to get .trc file, or is it what I thought.

You can use the -gh compiler command-line option, then you'll get a listing of memory leaks.

Michael.


More information about the fpc-pascal mailing list