Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a std::string contain embedded nulls?

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?

like image 628
WilliamKF Avatar asked May 16 '10 22:05

WilliamKF


People also ask

Can a string hold a null value?

The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all.

Does std::string include null terminator?

Actually, as of C++11 std::string is guaranteed to be null terminated. Specifically, s[s. size()] will always be '\0' .

Does C++ string have null character?

In C++ the std::string is an advancement of that array. There are some additional features with the traditional character array. The null terminated strings are basically a sequence of characters, and the last element is one null character (denoted by '\0').


2 Answers

Yes you can have embedded nulls in your std::string.

Example:

std::string s; s.push_back('\0'); s.push_back('a'); assert(s.length() == 2); 

Note: std::string's c_str() member will always append a null character to the returned char buffer; However, std::string's data() 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 a char* on the RHS. It will only add up until the null character.

For example:

std::string s = "hello"; s += "\0world"; assert(s.length() == 5); 

The correct way:

std::string s = "hello"; s += std::string("\0world", 6); assert(s.length() == 11); 

Storing binary data more common to use std::vector

Generally it's more common to use std::vector to store arbitrary binary data.

std::vector<char> buf; buf.resize(1024); char *p = &buf.front(); 

It is probably more common since std::string's data() and c_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.

like image 94
Brian R. Bondy Avatar answered Sep 24 '22 00:09

Brian R. Bondy


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.

like image 30
bmargulies Avatar answered Sep 21 '22 00:09

bmargulies