In C11 gets
has been substituted by gets_s
that has the following declaration:
char *gets_s(char *str, rsize_t n);
This function will read at most n-1
chars from stdin
into *str
. This is to avoid the buffer overflow vulnerability inherent to gets
. The function fgets
is also an option. From http://en.cppreference.com/w/c/io/gets:
The gets() function does not perform bounds checking, therefore this function is extremely vulnerable to buffer-overflow attacks. It cannot be used safely (unless the program runs in an environment which restricts what can appear on stdin). For this reason, the function has been deprecated in the third corrigendum to the C99 standard and removed altogether in the C11 standard. fgets() and gets_s() are the recommended replacements.
Never use gets().
Given that gets_s
is defined in an extension to the standard, only optionally implemented, you should probably write your programs using fgets
instead. If you use fgets
on stdin
your program will also compile in earlier versions of C. But keep in mind the difference in the behavior: when gets_s
has read n-1
characters it keeps reading until a new line or end-of-file is reached, discarding the input. So, with gets_s
you are always reading an entire line, even if only a part of it can be returned in the input buffer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…