[fpc-pascal] Pchar from constant string
Tomas Hajny
XHajT03 at hajny.biz
Fri Jun 30 13:14:00 CEST 2023
On 2023-06-30 11:11, Michael Van Canneyt via fpc-pascal wrote:
> On Fri, 30 Jun 2023, Hairy Pixels via fpc-pascal wrote:
>
>>
>>
>>> On Jun 30, 2023, at 9:03 AM, Hairy Pixels <genericptr at gmail.com>
>>> wrote:
>>>
>>> That's why that worked. Hmm with short strings the null terminator
>>> could be truncated when copying right? Something to look out for.
>>
>> this is what I meant about truncation. S is no longer null terminated
>> and now the pchar will fail when passed to C libraries right?
>>
>> var
>> s: String;
>> p: Pchar;
>> begin
>> s := 'hello';
>> p := @s;
>
> S will still be null-terminated for ansistrings and shortstrings.
>
> change to
>
> s:=s+s;
> p:=@s[1]; // and not @s
> writeln(p[Length(s)+1]=#0);
>
> and it will print TRUE.
However, there are operations valid for Pascal shortstrings which would
break this - as an example, older Pascal code used to change the S[0]
(i.e. the length byte) for a shortstring which wouldn't ensure that #0
follows such a moved end of the Pascal shortstring.
Moreover, note that #0 is a valid character in Pascal strings, i.e. in
general it is _not_ guaranteed that the trailing #0 after the end of the
string is the first one encountered when passing the string to a C code.
Obviously, you can ensure this in your own code, but it's important to
stress that neither the compiler nor the FPC RTL check or enforce full
equivalence of Pascal strings and C null-terminated strings.
Tomas
More information about the fpc-pascal
mailing list