char st[] = "0";
Pop Quiz: How big is st
?
Answer: Two chars
One for the "0
", and one for the null-terminator.
Then you go and overwrite the null terminator:
st[1] = '[';
...and try to construct a string
based on that:
std::string s (st);
The string
constructor which takes a const char*
is being invoked here, and the way it works is it looks for the null-terminator. Since you blew it away, it's going to run past the end of st
. Running past the end of st
evokes Undefined Behavior, and is the reason why you see garbage.
It's important to note that Undefined Behavior means anything can happen. "Anything" here includes "exactly what I want to happen". It doesn't necessarily that you'll get garbage output, or that your program will crash. Trying to reason out why UB manifests itself in this way or that is an unreasonable effort.