gets() function in C

it is a devil’s tool for creating buffer overflows

Because gets does not take a length parameter, it doesn’t know how large your input buffer is. If you pass in a 10-character buffer and the user enters 100 characters — well, you get the point.

fgets is a safer alternative to gets because it takes the buffer length as a parameter, so you can call it like this:

fgets(str, 10, stdin);

and it will read in at most 9 characters.

the problem is now some of my codes are not working anymore

This is possibly because fgets also stores the final newline (\n) character in your buffer — if your code is not expecting this, you should remove it manually:

int len = strlen(str);
if (len > 0 && str[len-1] == '\n')
  str[len-1] = '\0';

Leave a Comment