[fpc-pascal] PChar -> AnsiString -> PChar = memory leak?

Graeme Geldenhuys graemeg.lists at gmail.com
Thu Oct 29 14:44:09 CET 2009


On 29/10/2009, Mattias Gaertner <nc-gaertnma at netcologne.de> wrote:
>
>
> Text:=strnew(PChar(s));

You read my mind. I was going to ask if it's ok to cast a PString to a PChar.

Trying what you suggested, I get the following compiler error.

project1.lpr(20,11) Error: Incompatible types: got "PString" expected "PChar"

Changing my test code to the following solves the compiler error, but
now heaptrc reports that I have two memory leaks.

--------------------------
var
  Text: PChar;

procedure AppendText(const AText: string);
var
  s: string;
begin
  s := Text + AText;
  StrDispose(Text);
  Text := PChar(NewStr(s));
end;

var
  t: string;
begin
  t := 'hello';
  writeln('t=', t);
  Text := PChar(t);
  writeln('Text=', Text);
  AppendText(' world');
  writeln('Text=', Text);
end.
---------------------------

And the console output:

$ ./project1
t=hello
Text=hello
Text=P8
Heap dump by heaptrc unit
21 memory blocks allocated : 616/640
19 memory blocks freed     : 580/600
2 unfreed memory blocks : 36
True heap size : 131072
True free heap : 130720
Should be : 130776
Call trace for block $00007F42BFFFB3E0 size 8
  $0000000000400366 line 30 of project1.lpr
  $0000000000400178
Call trace for block $00007F42C0003840 size 28
  $0000000000400366 line 30 of project1.lpr
  $0000000000400178


Line 30 being the call to AppendText()




-- 
Regards,
  - Graeme -


_______________________________________________
fpGUI - a cross-platform Free Pascal GUI toolkit
http://opensoft.homeip.net/fpgui/



More information about the fpc-pascal mailing list