How to test if a string is pointing into read-only memory?
jfondren
julian.fondren at gmail.com
Tue Oct 12 08:19:01 UTC 2021
std.string.toStringz always allocates a new string, but it has
this note:
```d
/+ Unfortunately, this isn't reliable.
We could make this work if string literals are put
in read-only memory and we test if s[] is pointing into
that.
/* Peek past end of s[], if it's 0, no conversion necessary.
* Note that the compiler will put a 0 past the end of static
* strings, and the storage allocator will put a 0 past the end
* of newly allocated char[]'s.
*/
char* p = &s[0] + s.length;
if (*p == 0)
return s;
+/
```
and string literals weren't reliably in read-only memory as
recently as early 2017:
https://github.com/dlang/dmd/pull/6546#issuecomment-280612721
What's a reliable test that could be used in a toStringz that
skips allocation when given a string in read-only memory?
As for whether it's a necessarily a good idea to patch toStringz,
I'd worry that
1. someone will slice a string literal and pass the test while
not having NUL where it's expected
2. people are probably relying by now on toStringz always
allocating, to e.g. safely cast immutable off the result.
More information about the Digitalmars-d-learn
mailing list