From the D Blog -- Interfacing D with C: Strings Part One

Виталий Фадеев vital.fadeev at gmail.com
Thu May 27 03:52:32 UTC 2021


On Thursday, 27 May 2021 at 03:40:02 UTC, Виталий Фадеев wrote:
> On Wednesday, 26 May 2021 at 16:35:36 UTC, Ali Çehreli wrote:
>> On 5/25/21 9:00 PM, Виталий Фадеев wrote:
>>
>> >      immutable(char)* toStringz( ref string s )
>> >      {
>> >          if ( s.capacity <= s.length )
>> >              s.reserve( s.length + 1 );
>> >
>> >          char* cptr = cast( char* ) s.ptr; // C ptr
>> >          char* zptr = cptr + s.length;     // zero ptr
>> >          *zptr = '\0';
>>
>> That's undefined behavior because that location does not 
>> belong to the string. Here is an example that defeats the 
>> proposed toStringz:
>>
>> void main()
>> {
>>     string s;
>>     s = "D string";
>>
>>     auto c_string = toStringz( s );
>>
>>     auto other = s;
>>     other ~= 'X';    // <-- Seemingly unrelated operation
>>
>> // ...
>> }
>>
>> puts accesses that unrelated 'X' and more bytes after that:
>>
>>   C string: D stringX1^
>>
>> Ali
>
> Yes. True.
>
> reserve/capacity - not for all cases.

Zero terminator not keeped after concatenate source string with 
other string.

auto dString = "D string" ~ 2.to!string;
auto cString = dString.toStringz();
dString = dString ~ "new tail";
// cString[ $-1 ] != '\'0';



More information about the Digitalmars-d-announce mailing list