1

If I compile a code with gets, the compiler outputs a warning saying that the function shouldn't be used:

<source>:5:13: warning: 'char* gets(char*)' is deprecated [-Wdeprecated-declarations]
     gets(buf);
             ^
In file included from <source>:1:0:
/usr/include/stdio.h:577:14: note: declared here
 extern char *gets (char *__s) __wur __attribute_deprecated__;
              ^
/tmp/ccWRqB1K.o: In function `main':
/home/ce/<source>:5: warning: the `gets' function is dangerous and should not be used.

However, if I replace gets with scanf and a %s format string, it does not output such a warning:

int main()
{
    char buf[10];
    scanf("%s",buf);
}

If this program is compiled and I provide an input larger than 10 bytes, the program segfaults, and the buffer is overflown.

How can I understand this difference? Is scanf considered safe?

1 Answer 1

1

In general, scanf is not considered a safe function. It can be used safely or unsafely. In this case, your compiler is not issuing a warning since it does not have a lint that for an unbounded "%s" format string - i.e. it does not know that you are using it unsafely. On the other hand, it is hardly possible to use gets safely, as there is no way to provide a buffer length, so your compiler can with high confidence determine that you should not be using it.

To use scanf safely in your example, you'd need to provide the length in the format string, like so:

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

The buffer needs to be one byte larger than the length specifier in the format string to accomodate for the terminating NUL byte.

3
  • thanks I was a little confuse because in all the examples of buffer over flow they use gets
    – daniel
    Nov 26, 2020 at 7:01
  • FWIW, gcc after 5.5 does not support gets anymore: godbolt.org/z/zxdbY3
    – plonk
    Nov 26, 2020 at 7:12
  • @daniel Yes, gets is a typical one, but there are a lot of different ways you can get a buffer overflow. More tricky buffer overflows can be quite hard to spot!
    – plonk
    Nov 26, 2020 at 7:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .