[fpc-pascal] PChar -> AnsiString -> PChar = memory leak?
Aleksa Todorovic
alexionne at gmail.com
Thu Oct 29 14:07:24 CET 2009
On Thu, Oct 29, 2009 at 14:00, 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;
> Text := PChar(s);
> end;
>
No, you don't create memory leak. But your code neither works, because
s is local to AppendText, and PChar(s) becomes void after call to
AppendText - memory used by s will be deallocated, and since PChar(s)
= @s[1] Text would be invalid pointer. You will either need to convert
Text to SomeString, or do manual (de)allocation.
More information about the fpc-pascal
mailing list