Search code examples
c++stringstdstringnull-terminatedc-str

How does std::string's c_str() function return null-terminating string?


I cannot understand if char * returned from string.c_str() points to the same buffer (and not making any copy) how is it null terminated? does the function add null-terminator in the end of string? and what happens if buffer doesn't have any extra bytes to store it?

thanks.


Solution

  • Since C++11, strings are null-terminated internally, and both c_str() and data() return the same thing.