Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is string::c_str() no longer null terminated in C++11?

Tags:

c++

string

c++11

In C++11 basic_string::c_str is defined to be exactly the same as basic_string::data, which is in turn defined to be exactly the same as *(begin() + n) and *(&*begin() + n) (when 0 <= n < size()).

I cannot find anything that requires the string to always have a null character at its end.

Does this mean that c_str() is no longer guaranteed to produce a null-terminated string?

like image 859
Mankarse Avatar asked Sep 26 '11 10:09

Mankarse


People also ask

Is c_str () null-terminated?

c_str returns a "C string". And C strings are always terminated by a null character. This is C standard.

Is std::string always null-terminated?

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

Can c_str return null?

No. Since c_str returns a pointer p to a null-terminated array of characters, there must be some value i >= 0 such that p[i] == '\0' , and thus p cannot be null.

Does string end with null in C++?

In C the strings are basically array of characters. 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').


1 Answers

Strings are now required to use null-terminated buffers internally. Look at the definition of operator[] (21.4.5):

Requires: pos <= size().

Returns: *(begin() + pos) if pos < size(), otherwise a reference to an object of type T with value charT(); the referenced value shall not be modified.

Looking back at c_str (21.4.7.1/1), we see that it is defined in terms of operator[]:

Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()].

And both c_str and data are required to be O(1), so the implementation is effectively forced to use null-terminated buffers.

Additionally, as David Rodríguez - dribeas points out in the comments, the return value requirement also means that you can use &operator[](0) as a synonym for c_str(), so the terminating null character must lie in the same buffer (since *(p + size()) must be equal to charT()); this also means that even if the terminator is initialised lazily, it's not possible to observe the buffer in the intermediate state.

like image 97
Mikhail Glushenkov Avatar answered Sep 19 '22 15:09

Mikhail Glushenkov