Which one of the following is safe regarding buffer overflow?
char buf[10] = {0};
scanf("%10s", buf);
or
char buf[10] = {0};
scanf("%9s", buf);
From what I've read I'm going for the second (sizeof minus one), but the matter is quite subtle and I've seen code suggesting either. Any volunteer to quote the standard?
is unsafe. You have to take into account the string null terminator.
is safe.
The C standard states that:
That is, the maximum field width represents how many characters there can be in the input. The extra zero value at the end is not part of the input and needs an additional space.
The GNU libc manual makes this point explicit:
So, the only safe version is
scanf("%9s", buf)
.