1

It is possible to call .c_str() for a C++ const string.

In order to efficiently implement this, it means that it must internally store an extra null character. (Otherwise, copying or modifying data would be required for a .c_str() call)

Therefore a C++ string is always null-terminated, even before calling c_str().

Right? Or wrong?

CaptainCodeman
  • 1,922
  • 2
  • 18
  • 23
  • 3
    Accepted answer in linked question is a bit outdated. The better one - https://stackoverflow.com/a/11752722/4074081: `In C++11 and later, mystring.c_str() is equivalent to mystring.data() is equivalent to &mystring[0], and mystring[mystring.size()] is guaranteed to be '\0'.` – dewaffled Dec 22 '20 at 09:18

2 Answers2

2

Yes, it's required from C++11 onwards.

For a std::string s, s[s.size()] must be 0. (Note that the behaviour on attempting to modify that element is undefined.)

Note that s is allowed to contain 0 before that final terminator. In this respect, it differs from a plain C-style string.

Reference: https://en.cppreference.com/w/cpp/string/basic_string

Bathsheba
  • 227,678
  • 33
  • 352
  • 470
1

Prior to C++11, the string’s data buffer was NOT required to be null-terminated, or even contiguous. An implementation of c_str() was allowed to copy the data to a separate contiguous null-terminated buffer. However, in practice, no implementation is known to actually have done this, the data buffer was commonly contiguous and null-terminated for efficiency.

Since C++11, the data buffer is required to be contiguous and null-terminated, specifically to keep the implementation of the c_str() and data() methods simple.

Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696