From the D Blog -- Interfacing D with C: Strings Part One
Ali Çehreli
acehreli at yahoo.com
Wed May 26 16:35:36 UTC 2021
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
More information about the Digitalmars-d-announce
mailing list