Why add a string type to C?

One of the caveats of C is its lack of string type. The only way strings can be defined is by the use of a character array, which isn’t always the best solution. The biggest problem with strings in C (for the novice anyway) is the end-of-string (NULL) terminator ‘\0’. Mainly it causes problems because a declaration like this:

char str[100];

Only technically stores 99 characters. To the experienced programmer, this isn’t an issue, to the novice it is. The other issue is that people see the “shortcut” of using:

char *str;

Which of course seems very seductive because the novice does not realize that memory must be allocated – and frankly C does allow it to happen. Consider the following two segments of code:

char *str = "Luke Skywalker? I Thought He Was A Myth.";
printf("%s", str);
char *str;
scanf("%s", str);
printf("%s", str);

The first piece of code works because a text string has been associated with the “pointer to char”, str. But it works because this is a string literal, i.e. stored in read-only memory. Try to modify the string, and an error will occur. The second piece of code does not work on most systems. In fact on my MacBook it produces a segmentation fault, and on a Raspberry Pi it produces a bus error.

Sometimes when a algorithm involving a string is created, the programmer forgets to add a terminating ‘\0’, which can lead to problems. Consider the following snippet of code.

char str[10];
str[0] = 'J';
str[1] = 'e';
str[2] = 'd';
str[3] = 'i';

Here str may cause undefined behaviour if used as a string, because the string has not been NULL-terminated. Ironically on many modern compilers, it seems as though somehow a string terminator  is automatically added.

C would be better serviced by a dedicated string type.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s