1

was reading the Head first C book and stumbled across the author saying gets() to be a bad practice

gets() is a function that’s been around for a long time. But all you really need to know is that you really shouldn’t use it.

why is it considered a bad practice?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Chainsaw
  • 11
  • 7
  • 2
    The `gets` function is no longer part of C. It's so awful it was removed. – James McNellis Mar 15 '14 at 05:19
  • 3
    It is a function that ***CANNOT*** be safely used, because it is given a buffer of characters to write into but no maximum number of characters to read. If you provide too many characters you will end up with corruption. On no account use it; Prefer `fgets()`. – Iwillnotexist Idonotexist Mar 15 '14 at 05:20
  • @IwillnotexistIdonotexist: There's one safe way to use `gets`, when `stdin` is known to be a file fully under your control. However this situation is sufficiently unusual (and, I might say, artificial) not to be worth considering, and for practical purposes `gets` is *always* unsafe. – R.. GitHub STOP HELPING ICE Mar 15 '14 at 05:56

2 Answers2

5

Consider

#include<stdio.h>
int main()
{
    char buffer[100];
    gets(buffer);
    printf("The input is %s",buffer);
}

When user types input of length within 99 then there is no problem. But when user types more than 99 characters it tries to write into memory it doesn't own.

The worst thing is it causes abnormal behaviour and the program terminates without any information which leaves user baffled about the current situation

An alternative way is to use char *fgets(char *s, int size, FILE *stream); function

Update: As pointed by @pmg : gets() removes newline while fgets() retains the new line

Krishna M
  • 1,135
  • 2
  • 16
  • 32
  • Try 99 not 100 (null character) – Ed Heal Mar 15 '14 at 05:21
  • 1
    @IwillnotexistIdonotexist: [`gets()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/gets.html) removes the newline; [`fgets()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html) retains it. – pmg Mar 15 '14 at 09:18
  • @pmg Wasn't aware of this further asymmetry between `fgets()` and `gets()`. I'll pull my comment. – Iwillnotexist Idonotexist Mar 15 '14 at 14:51
4

gets is prone to buffer overruns (i.e. memory corruption etc).

fgets over comes this by having passing in the size of the buffer

Ed Heal
  • 59,252
  • 17
  • 87
  • 127