www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to print or check if a string is "\0" (null) terminated in the D

reply BoQsc <vaidas.boqsc gmail.com> writes:
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.
Apr 06 2022
next sibling parent Andrea Fontana <nospam example.com> writes:
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.
string literals are zero-terminated in d. If you need to pass a D string to a C function use toStringz() https://dlang.org/library/std/string/to_stringz.html
Apr 06 2022
prev sibling next sibling parent Stanislav Blinov <stanislav.blinov gmail.com> writes:
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.
Apr 06 2022
prev sibling parent Salih Dincer <salihdb hotmail.com> writes:
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 
 [...]
If you suspect overflow, you can try string wrapping.
Apr 06 2022