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

Mattias Gaertner nc-gaertnma at netcologne.de
Thu Oct 29 14:09:33 CET 2009


On Thu, 29 Oct 2009 15:00:53 +0200
Graeme Geldenhuys <graemeg.lists at gmail.com> wrote:

> Hi,
> 
> Do I create a memory leak if I cast a PChar it a AnsiString. Then
> append text to the AnsiString and then cast it back to the original
> PChar?
> 
> eg:
> var
>   Text: Pchar;    <-- global var containing text.
> 
> procedure AppendText(const AText: string);
> var
>   s: string;
> begin
>   s := Text + AText;

ok

>   Text := PChar(s);

wrong, because the local s is the only one having increased the ref
count ...

> end;

... therefore the 'end' will free the ansistring.


BTW 'text' is a system type.

> I'm busy converting a old program from OS/2 days that used PChar
> exensively. I'm slowly but surely converting this code to AnsiString.
> But as a quick fix, am I allowed to do what is shown above? Without
> causing memory leaks or something else?
 

Mattias



More information about the fpc-pascal mailing list