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?

1
  • 3
    Accepted answer in linked question is a bit outdated. The better one - 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'. Commented Dec 22, 2020 at 9:18

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Just for reference, do you possibly have a link that confirms this?
@CaptainCodeman: I've added a reference. cppreference is pretty much a proxy for the standard, and is simpler to read.
Thank you, that is much appreciated.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.