Bound input to the destination
suggest changeAn unbounded %s conversion can write beyond its destination and cause undefined behavior:
char name[8];
scanf("%s", name); /* Unsafe: the input length is unbounded. */
A field width limits the number of characters stored. Reserve one byte for the terminating null character and check whether conversion succeeded:
char name[8];
if (scanf("%7s", name) != 1) {
/* Handle invalid input or end-of-file. */
}
The width is part of the format string, not a separate argument, and must match the destination capacity. For line-oriented input, fgets is often clearer:
char name[8];
if (fgets(name, sizeof name, stdin) == NULL) {
/* Handle an input error or end-of-file. */
}
If the input line is longer than the array, fgets stores only its first part and leaves the remainder in the stream. Detect the missing newline and decide whether to keep reading or reject the input.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents