gets() function in C

c

Solution

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 code 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';

Problem

I thought it is pretty cool to use the `gets()` function because it is like the `scanf()` wherein I could get an input with whitespace. But I read in one of the threads (student info file handling) that it is not good to use because according to them, it is a devil's tool for creating buffer overflows (which I don't understand) If I use the `gets()` function, I could do this. ENTER YOUR NAME: `Keanu Reeves`. If I use the `scanf()`, I could only do this. ENTER YOUR NAME: `Keanu` So I heed their advice and replaced all my `gets()` code with `fgets()`. The problem is now some of my code are not working anymore...are there any functions other than `gets()` and `fgets()` which could read the whole line and which ignores the whitespace.

Original source

Related problems