Home > Backend Development > C++ > body text

Does C 11\'s `string::c_str()` Still Guarantee a Null-Terminated String?

Mary-Kate Olsen
Release: 2024-10-27 15:35:02
Original
343 people have browsed it

 Does C  11's `string::c_str()` Still Guarantee a Null-Terminated String?

Is C 11's string::c_str() Function No Longer Null-Terminated?

In C , the basic_string class provides various methods to access its characters. One of these methods, c_str(), has been a source of confusion since C 11. Prior to C 11, c_str() was responsible for returning a null-terminated character array representing the string's contents.

However, in C 11, the definition of basic_string::c_str() has changed. It is now defined to be the same as basic_string::data, which in turn returns a pointer to the beginning of the string's internal character buffer. This raised a question: does this change imply that c_str() no longer guarantees a null-terminated string?

The Answer: Strings Require Null-Terminated Buffers Internally

The answer to this question is no. Despite the changes in C 11, strings are still required to use null-terminated buffers internally. This is evident from the definition of the operator[] method (21.4.5) in the C standard:

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.
Copy after login

c_str() is defined in terms of operator[]:

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

Since c_str() and data are both required to be O(1) operations, the implementation is effectively forced to use null-terminated buffers. Additionally, the return value requirement for operator[] ensures that c_str() returns a pointer to a null-terminated buffer. Therefore, c_str() continues to provide a null-terminated string, despite the changes in C 11.

The above is the detailed content of Does C 11\'s `string::c_str()` Still Guarantee a Null-Terminated String?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!