As for considering the size needed to store a char *
string, many of the C stdlib string functions will tell you the length they require if you pass them NULL
. You can call this before allocating storage for the string to know how much storage you need:
std::cout << "You need a buffer that can store "
<< sprintf (NULL, "%d is one number", 1) + 1
<< " characters to safely store your string."
<< std::endl;
Another solution is to use something like snprintf (...)
, which guarantees that it will truncate the output so that it will not overrun your buffer:
snprintf (buffer, 1, "%d is one number", 1);
// ~~~
// Length of buffer
In your case, the buffer is only 1 character long so it only has enough space to store the null terminator; not particularly useful.