[fpc-devel] Array of char

Jonas Maebe jonas.maebe at elis.ugent.be
Wed Feb 25 18:08:16 CET 2015

On 25/02/15 17:02, thaddy at thaddy.com wrote:
> @ Florian.
> You closed the typecast from array of char to string issue.


> Maybe you are right,
> I just can prove that every d2-xe7 adds a #0, so a cast (partially,
> agreed) works in delphi and not in fpc.

It's unrelated to the terminating #0. It's about the hidden length and
other metadata that is stored before the dynamic array and the string.
This data is not compatible in either FPC or in Delphi. Delphi happens
to store the length data in the same way, but other data for strings is
not present with dynamic arrays (as your own test in comment 0081403 shows).

If you were to pass such typecasted arrays to arbitrary Delphi routines
that expect ansistrings, you'll also get garbage results there in
certain cases (because of missing code page information, so arbitrary
data before the dynamic array will be interpreted as code page -- in
fact, in principle this can even cause crashes, in case the memory
coming before the dynamic array has not been mapped).

You'll probably also get memory corruption if you assign the result of
the typecast to an ansistring, then set the dynamic array reference to
nil (so the ansistring contains the last reference) and then set the
ansistring to an empty string (because Delphi will then probably try to
free a pointer that starts 16 or 32 bytes before the "string" data,
while in case of a dynamic array it starts fewer bytes before the array
data -- at least in FPC, but probably in Delphi too).

> I suggest you reconsider this. The raw pointer cast should work, which
> means an array of char should have a hidden terminator as well as a
> hidden pre.

A dynamic array and an ansistring are two completely unrelated types.
There is no reason why an explicit typecasts between them should work.


More information about the fpc-devel mailing list