For regular C strings, a null character '\0'
signifies the end of data.
What about std::string
, can I have a string with embedded null characters?
For regular C strings, a null character '\0'
signifies the end of data.
What about std::string
, can I have a string with embedded null characters?
Yes. A std::string is just a
vector<char>
with benefits.However, be careful about passing such a beast to something that calls
.c_str()
and stops at the 0.Yep this is valid.
You can have a null character in the middle of the string.
However, if you use a std::string with a null character in the middle with a c string function your in undefined behaviour town - and nobody wants to be there!!!:
Yes you can have embedded nulls in your
std::string
.Example:
Note:
std::string
'sc_str()
member will always append a null character to the returned char buffer; However,std::string
'sdata()
member may or may not append a null character to the returned char buffer.Be careful of operator+=
One thing to look out for is to not use
operator+=
with achar*
on the RHS. It will only add up until the null character.For example:
The correct way:
Storing binary data more common to use std::vector
Generally it's more common to use
std::vector
to store arbitrary binary data.It is probably more common since
std::string
'sdata()
andc_str()
members return const pointers so the memory is not modifiable. with &buf.front() you are free to modify the contents of the buffer directly.You can, but why would you want to? Embedding NUL in an std::string is just asking for trouble, because functions to which you pass an std::string may very well use it's c_str() member, and most will assume that the first NUL indicates the end of the string. Hence this is not a good idea to do. Also note that in UTF-8, only '\0' will result in a 0, so even for i18n purposes, there is no justification for embedding NULs.