If someone complains about gets (), why not do the same with scanf ("% s", ...)?

From man gets:

Never use gets (). Because it is impossible to say without knowing the data in advance how many gets () characters will be read, and because gets () will continue to store characters beyond the end of the buffer, it is extremely dangerous to use. It was used to hack computer security. Use fgets () instead.

Almost everywhere I see that scanfis used in a way that should have the same problem ( buffer overflow / buffer overflow ) scanf("%s",string). Does this problem exist in this case? Why is scanfthere no link on the page ? Why doesn't gcc warn when compiling this with -Wall?

ps: I know there is a way to specify the maximum length of a string in a format string using scanf:

char str[10];
scanf("%9s",str);

edit: I am not asking to determine if the previous code is correct or not. My question is: if it’s scanf("%s",string)always wrong, why there are no warnings, and there is nothing about it on the manual page?

+5
source share
5 answers

The answer is that no one wrote code in GCC to receive this warning.

As you noticed, a warning for a specific case "%s"(without field width) is quite appropriate.

, scanf(), vscanf(), fscanf() vfscanf(). sscanf() vsscanf(), . , "scanf-style-format-string"; "fscanf-style-format-string" "sscanf-style-format-string".

, GCC, (, , glibc).

+5

gets() . scanf() , . , , , (, scanf() , , - , ); , , .

+4

scanf, ! , . , GCC, , . , , , C. , , :

char* str;
size_t size;
scanf("%z", &size);
str = malloc(size);
scanf("%9s"); // how can the compiler determine if this is a safe call?!

, scanf, . gets .

+3

It may just be that scanf will allocate space on the heap depending on how much data is being read. Since it does not allocate a buffer and then reads until a null character is read, it does not run the risk of overwriting the buffer. Instead, it reads its own buffer until a null character is found, and presumably copies this buffer to another out of the right size at the end of reading.

-4
source

All Articles