From the D Blog -- Interfacing D with C: Strings Part One
Виталий Фадеев
vital.fadeev at gmail.com
Thu May 27 03:40:02 UTC 2021
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.
More information about the Digitalmars-d-announce
mailing list