C Programming/stdio.h/gets

  is a function in the C standard library, declared in the header file, that reads a line from the standard input and stores it in a buffer provided by the caller.

Use of  is strongly discouraged. It is left in the C89 and C99 standards for backward compatibility (but officially deprecated in late revisions of C99). It is removed from the C11 standard and instead a range checking alternative  is introduced. Many development tools such as GNU ld emit warnings when code using  is linked.

Implementation
It might be implemented as follows (using ):

The programmer must know a maximum limit for the number of characters  will read so he can ensure the buffer is big enough. This is impossible without knowledge of the data. This design flaw leads to bugs and opens a gate for exploiting computer security through a buffer overflow. Many sources advise programmers to never use  in new programs.

Alternatives
Other line input functions may be used instead of, so as to avoid buffer overflow bugs. A simple alternative is. When replacing code of the form

with code of the form

one must keep in mind that the  call differs from   not only in buffer overflow protection, but also in that   preserves the terminating newline (if the input line is terminated by a newline), while   discards it.

The first edition of The C Programming Language did not use  but instead described a much safer function , which would not overflow the buffer and would return the useful information of how many bytes were read (which would allow NUL to be typed) or -1 on error or EOF. It is unclear why gets ended up in the C standard library rather than this function.

POSIX-2008 defines  that reallocates the buffer as needed to hold the input line (note the extra level of indirection on the buffer and size).

The C1X proposal has a replacement function  that returns an empty string and consumes the whole current line if the line does not fit in   characters.

Safe use
Safe use of  requires the programmer to ensure that buffer overflows cannot be a problem. The only portable way is to somehow make sure the input file cannot contain lines longer than the buffer, such as by ensuring that the file was created by a program that cannot write such lines. There are a number of other relatively complicated ways to protect from buffer overflows, with varying degrees of portability. One possibility is to use a guard page to protect memory. Alone, this turns exploitable buffer overflows into mere crashes. In combination with an exception handler, such as one involving  and , the guard page can allow graceful error handling.