Forgetting the Null Character That Terminates Strings

Remember that strings end with a null character in C. If you declare this five-character array,

char sample[5];

the compiler allocates five bytes of memory for the array. If you try to store the string "Hello" in the array like this,

strcpy( sample, "Hello" );

you'll overrun the array's bounds. The string "Hello" contains six characters (five letters and a null character), so it's one byte too big to fit in the sample array. The strcpy overwrites one byte of memory outside the array's storage.

It's easy to make this error when allocating memory for a string, too:

char str[] = "Hello";

char *ptr;

ptr = malloc( strlen( str ) );/* Error! */

if( ptr == NULL )

exit( 1 );

else

strcpy( ptr, str );

This time the error occurs in the call to the malloc function, which allocates memory to a pointer prior to a string copy. The strlen function returns the length of a string not including the null character that ends the string. Since the amount of memory allocated is one byte too small, the strcpy operation overwrites mem-ory, just as in the previous example.

To avoid the problem, add 1 to the value returned by strlen:

ptr = malloc( strlen( str ) + 1 );