Why is this an issue?
The %s
placeholder is used to read a word into a string.
By default, there is no restriction on the length of that word, and the developer is required to pass a sufficiently large buffer for storing
it.
No matter how large the buffer is, there will always be a longer word.
Therefore, programs relying on %s
are vulnerable to buffer overflows.
A field width specifier can be used together with the %s
placeholder to limit the number of bytes which will by written to the
buffer.
Note that an additional byte is required to store the null terminator.
Noncompliant code example
char buffer[10];
scanf("%s", buffer); // Noncompliant - will overflow when a word longer than 9 characters is entered
Compliant solution
char buffer[10];
scanf("%9s", buffer); // Compliant - will not overflow
Resources