Legal to overwrite std::string’s null terminator?

Unfortunately, this is UB, if I interpret the wording correct (in any case, it’s not allowed):

§21.4.5 [string.access] p2

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.

(Editorial error that it says T not charT.)

.data() and .c_str() basically point back to operator[] (§ [string.accessors] p1):

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

Leave a Comment