Returning a PChar Local Variable

From RAD Studio
Jump to: navigation, search

Go Up to String to PChar Conversions


A common error when working with PChar is to store a local variable in a data structure, or return it as a value. When your routine ends, the PChar disappears because it is a pointer to memory, and not a reference counted copy of the string. For example:

function title(n: Integer): PChar;
var
  s: string;
begin
  s := Format('title - %d', [n]);
  Result := PChar(s); // DON'T DO THIS
end;

This example returns a pointer to string data that is freed when the title function returns.

See Also