Graeme Geldenhuys 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;
I don't think a memory leak. But a problem yes.
Text will have random content afterwards!
s := Text + AText;
"s" will be the new string. => new memory allocated
Text := PChar(s);
"Text" will be a pointer to the memory allocet by "s"
At the end of the procedure "s" will be freed (because it's a local
string, so it has no longer any references)
"Text" will then point to unallocated memory (still holding the string)
=> but as soon as your program does anything, the memory may be reused,
and "text" points to random data.
If PChar points to a string, then the strig must be kept as long as
pchar is used. (I run into that issue myself, last year....)
Martin
_______________________________________________
fpc-pascal maillist - fpc-pascal@lists.freepascal.org
http://lists.freepascal.org/mailman/listinfo/fpc-pascal