"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Is C++11\'s `string::c_str()` Still Null-Terminated?

Is C++11\'s `string::c_str()` Still Null-Terminated?

Published on 2024-11-07
Browse:337

Is C  11\'s `string::c_str()` Still Null-Terminated?

Does C 11's string::c_str() Eliminate Null Termination?

In C 11, string::c_str is no longer guaranteed to produce a null-terminated string.

Reason:

In C 11, string::c_str is defined as identical to string::data, which in turn is defined as equivalent to *(begin() n) for 0

Consequences:

This implies that string::c_str() may no longer return a null-terminated string, leading to potential errors in scenarios that assume such termination.

Solution:

The solution is to use string::c_str() only for compatibility with legacy code. For new code, use string::data() instead. While string::data() does not return a null-terminated string, it returns a pointer to the underlying buffer, which is guaranteed to be null-terminated internally.

Implementation Details:

Internally, strings are now required to use null-terminated buffers. The operator[] definition in section 21.4.5 requires that for size()

Additional Notes:

  • &operator[](0) can be used as a synonym for c_str().
  • The terminating null character must lie in the same buffer as the string data, as *(p size()) must be equal to charT(). Thus, even if the null character is initialized lazily, it is not possible to observe the buffer in an intermediate state.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3