A valid C string consists of an array of zero or more characters plus an additional null character. Thus, the shortest possible string must contain at least one character. Remember that the function strlen() returns the size of the string excluding the null terminator. Therefore, in the following code fragment:
char arr[3] = "hi" ; // null appended automatically n = strlen("hi"); // equals 2, not three
the value of n is 2 rather than 3. This can lead to the following bug:
char * strduplicate(const char *s ) { int n = strlen(s); char * p = new char [n]; // oops, array's too short strcpy(p, s); // undefined behavior }
The char array allocated on the free store is one char too short. Since strcpy() automatically appends a null character at the end of the p, it causes a buffer overflow?the final null is written to an out of bound element. Therefore, remember always to make room for the null character:
int n = strlen(s) + 1; // OK