Does std::string's c_str() method always return a null-terminated string?
Yes.
It's specification is:
Returns: A pointer p
such that p + i == &operator[](i)
for each i
in [0,size()]
.
Note that the range specified for i
is closed, so that size()
is a valid index, referring to the character past the end of the string.
operator[]
is specified thus:
Returns: *(begin() + pos)
if pos < size()
, otherwise a reference to an object of type T
with value charT()
In the case of std::string
, which is an alias for std::basic_string<char>
so that charT
is char
, a value-constructed char
has the value zero; therefore the character array pointed to by the result of std::string::c_str()
is zero-terminated.