#dbugfix 15136
Dennis
dkorpel at gmail.com
Fri Jan 18 23:26:07 UTC 2019
On Friday, 18 January 2019 at 20:45:05 UTC, Steven Schveighoffer
wrote:
> TBH, fixing toStringz to not be hacky would make it so the
> manifestation happened every time :)
In that case it would be consistent. Now the culprit appeared to
be __FUNCTION__ and the test case couldn't be reduced further. It
can be made clear that toStringz is an allocating function, and
if @nogc is important some other options are available. In
arsd/simpledisplay.d, toStringz is simply defined as:
```
const(char)* toStringz(string s) { return (s ~ '\0').ptr; }
```
You may lose the avoidance of appending 75% of the time, but it
won't allow for buffer overflows. When performance is important,
other facilities are useful:
- string literals can already safely be passed
- I don't know if std.file.readText is guaranteed
null-terminated, but a zero-terminated version/option could be
made if there isn't one already
- if a string is constructed by concatenating strings, a null
byte can be appended if there's enough capacity without needing
to reallocate
The hardest part is when the string origin is unknown, i.e.
passed as parameter.
If I make a convenience function that takes a D string and passes
it to a C library function, then even when I pass a string
literal, the function only sees a slice and doesn't know whether
the zero byte at the end belongs to the string or not. A special
type for zero-terminated strings would be needed, or a way to
recognize pointers in a readonly section.
More information about the Digitalmars-d
mailing list