Search code examples
c++cdeprecatedgets

Is gets() officially deprecated?


Based on the most recent draft of C++11, C++ refers to ISO/IEC 9899:1999/Cor.3:2007(E) for the definitions of the C library functions (per §1.2[intro.refs]/1).

Based on the most recent draft of C99 TC3, The gets function is obsolescent, and is deprecated. (per §7.26.9/2)

Can I safely say that gets() is deprecated in both C and C++?


Solution

  • Does it matter? The only way you can ever use gets is if stdin is known to be attached to a file whose contents you have full control over. This condition is almost impossible to satisfy, especially on multiprocess systems where other processes may modify files asynchronously with respect to your program. Therefore, for all practical purposes, any program using gets has undefined behavior (i.e. there are possible inputs/environmental conditions for which it will have undefined behavior), and in particular UB which is likely to lead to privilege compromise if your program has higher privileges than the provider of the data.

    Edit: OK, here's one safe use of gets, about the only one I can think of right off...

    if (feof(stdin)) gets(buf);
    

    Of course some buggy implementations (possibly including glibc..?) permit reads even when the EOF indicator is already set for a stream, so....