Theory
Common mistakes
With strings most bugs are the same one: writing more than fits, or forgetting '\0'.
Common mistakes
- No room for
'\0'.char t[3] = "Ona";compiles without any warning, but the'\0'didn't fit:printf("%s", t)prints garbage after "Ona". The array is at least the text + 1. ==instead ofstrcmp.if (name == "Ona")compares addresses:comparison with string literal results in unspecified behavior. Writestrcmp(name, "Ona") == 0.=on an array.city = "Kaunas";givesassignment to expression with array type. Copy withsnprintf.strcpyinto an array that's too small.strcpy(t, "Kaunas")withchar t[4]giveswriting 7 bytes into a region of size 4 overflows the destination. The compiler only catches it when the text is known in advance; for typed text nothing does. Hencesnprintf.scanf("%s")andgets. No size check at all. Onlyfgetswithsizeof.- A forgotten
'\n'. Afterfgetsthe line ends with'\n':strcmp(t, "q")will never be 0 until you cut it off. - Leftovers in the input. The rest of a too-long line is read by the next
fgets. Throw it away up to'\n'. - Changing a literal.
char *s = "Ona"; s[0] = 'A';compiles, but the program crashes: literals live in read-only memory. Writeconst char *sand the compiler won't allow it. strlencounts bytes.strlen("ąžuolas")is 9. Count room in an array in bytes.isdigit(t[i])without(unsigned char). The bytes of Lithuanian letters are negative in achar, and a negative value is undefined behaviour for these functions.