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:
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:
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; str = 'J'; str = 'e'; str = 'd'; str = '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.