[fpc-pascal] PChar -> AnsiString -> PChar = memory leak?
Mattias Gaertner
nc-gaertnma at netcologne.de
Thu Oct 29 14:59:02 CET 2009
On Thu, 29 Oct 2009 15:44:09 +0200
Graeme Geldenhuys <graemeg.lists at gmail.com> wrote:
> 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.
Yes.
But it will not change the reference count.
> Trying what you suggested, I get the following compiler error.
>
> project1.lpr(20,11) Error: Incompatible types: got "PString" expected
> "PChar"
It compiles here. Probably you use some special units.
> 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));
ok
Not very fast, but ok.
> end;
>
> var
> t: string;
> begin
> t := 'hello';
> writeln('t=', t);
> Text := PChar(t);
> writeln('Text=', Text);
> AppendText(' world');
> writeln('Text=', Text);
> end.
Graeme, why don't you just change the type of 'Text' to string?
This does not change the reference count:
Text := PChar(t);
The string is not duplicated. And StrDispose can not free that.
And 'Text' is not freed at the end.
Mattias
More information about the fpc-pascal
mailing list