Why does this string implementation allocate one more character than there are characters in the string?

Viewed 63
String::String(const String& old_str)    
{ 
    size = old_str.size; 
    s = new char[size+1]; 

Why do we use size+1 here to allocate memory, not size?

1 Answers

In C, strings all end with a null-byte, represented by \0 inside a string. The size attribute returns the size not accounting for the nullbyte, so you must allocate size+1 bytes so the terminating nullbyte doesn't overflow. Read more about null-terminated strings here.

Related