What is gets() equivalent in C11?

c c11
Shash picture Shash · Oct 15, 2012 · Viewed 7k times · Source

From cplusplus.com

The most recent revision of the C standard (2011) has definitively removed this function from its specification

The function is deprecated in C++ (as of 2011 standard, which follows C99+TC3).

I just wanted to know what is the alternative to gets() in C11 standard?

Answer

Joni picture Joni · Oct 15, 2012

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.