When in doubt, turn to Stackoverflow…
I’m having a problem with string allocation. My goal is to store n length of a passed quoted string. I check m_p for null because I think in debug mode MS likes to set the address to 0xcccccccc instead of 0x00000000.
I passed 1 into length. But when I allocate it using new, I’m getting about 15 symbol characters in m_p. How can this be if m_size = lenth + 1 is 2? I would expect it to allocate only two cells. How can I limit it to length + 1?
String::String(const char *str, int length) {
m_size = length + 1; // make room for null-terminated string
if (m_p != NULL)
m_p = NULL;
try
{
m_p = new char[m_size];
}
catch (bad_alloc e)
{
throw e;
}
strncpy(m_p, str, m_size);
}
If you want to store n characters of a passed quoted string, you need to take into account that strncpy doesn’t append null character if the length of the source string is greater than or equal to the length argument. So you have to take care of it: