Scanf field width field overflow

Which of the following conditions is safe for buffer overflows?

char buf[10] = {0}; scanf("%10s", buf); 

or

 char buf[10] = {0}; scanf("%9s", buf); 

From what I read, I'm going to the second one (sizeof minus one), but the question is pretty subtle, and I saw code suggesting either. Any volunteer to quote the standard?

+6
source share
2 answers

The C> standard states that:

An input element must be defined as the longest sequence of input bytes (up to any given maximum field width that can be measured in characters or bytes depending on the conversion specifier), which is the initial subsequence of the matched sequence.

That is, the maximum field width indicates how many characters can be input. The extra zero at the end is not part of the input and requires additional space.

The GNU libc user guide makes this point explicit:

String conversions in strings retain the null character to mark the end of input; maximum field width does not include this limiter.

So, the only safe version is scanf("%9s", buf) .

+9
source
 char buf[10] = {0}; scanf("%10s", buf); 

unsafe. You must consider the null string delimiter.

 char buf[10] = {0}; scanf("%9s", buf); 

is safe.

+2
source

Source: https://habr.com/ru/post/972204/


All Articles