Although you already got a correct comment saying the behaviour is undefined, there is something worthy of an actual answer too.
A C++ string
object can contain any sequence of characters you like. A C-style string is terminated by the first '\0'
. Consequently, a C++ string
object must store the size somewhere other than by searching for the '\0'
: it may contain embedded '\0'
characters.
#include <string>
#include <iostream>
int main() {
std::string s = "abc";
s += '\0';
s += "def";
std::cout << s << std::endl;
std::cout << s.c_str() << std::endl;
}
Running this, and piping the output through cat -v
to make control characters visible, I see:
abc^@def abc
This explains what you're seeing: you're overwriting the '\0'
terminator, but you're not overwriting the size, which is stored separately.
As pointed out by kec, you might have seen garbage except you were lucky enough to have an additional zero byte after your extra characters.