It "works" because sprintf
expects a char*
as its first argument, and that what's you are giving him.
However, you really just allocated one char
so writing more than one char
to it is undefined behavior. It could be that more than one byte gets allocated depending on... the compiler, the host architecture, and so on but you can't rely on it. Actually, anything could happen and you don't want to base your code on such assumptions.
Either allocate more space for your string buffer, or better use a more "modern" approach. In your case it could be something like:
std::string s = std::to_string(300);
// Or, C++03
std::string s = boost::lexical_cast<std::string>(300);
(We are not talking about performance here, but the initial code being incorrect, we could hardly compare anyway).
As an added bonus, this code doesn't leak any memory because std::string
takes care of freeing its internal memory upon destruction (s
being allocated on the stack, this will happen automatically when it goes out of scope).