How to print or check if a string is "\0" (null) terminated in the D programming language?
Stanislav Blinov
stanislav.blinov at gmail.com
Wed Apr 6 10:35:13 UTC 2022
On Wednesday, 6 April 2022 at 08:55:43 UTC, BoQsc wrote:
> I have a feeling that some parts of my code contains
> unterminated strings and they do overflow into other string
> that is to be combined. I'd like to take a look at strings,
> analyse them manually and see if any of them end up terminated
> or not.
>
> Please provide any relevant examples of how you do this.
In general, you shouldn't do that. In D, a `string`, `wstring`
and `dstring` are slices of corresponding character types, and
are *not* null-terminated (and in fact can contain 0 within their
representation). However, as Andrea Fontana points out, string
literals are null-terminated (but note that the terminator itself
isn't included in a `string` initialized with such a literal),
and also convert to pointers - these two properties allow using
them as arguments to C functions.
Thus, since null terminator isn't normally included as part of a
string, you'd have to read past array bounds to check if there's
a 0 there, and doing so leads to undefined behavior.
In fact, you should simply assume that any D string you encounter
is not null-terminated. And if you want to ensure you're always
passing around null-terminated strings, you should either use the
greedy allocating functions such as `toStringz`, or perhaps make
your own type that always allocates extra space for a 0.
More information about the Digitalmars-d-learn
mailing list