Because gets doesn't do any kind of check while getting bytes from stdin and putting them somewhere. A simple example:
char array1[] = "12345";
char array2[] = "67890";
gets(array1);
Now, first of all you are allowed to input how many characters you want, gets
won't care about it. Secondly the bytes over the size of the array in which you put them (in this case array1
) will overwrite whatever they find in memory because gets
will write them. In the previous example this means that if you input "abcdefghijklmnopqrts" maybe, unpredictably, it will overwrite also array2
or whatever.
The function is unsafe because it assumes consistent input. NEVER USE IT!
Safer method is fgets()
So, you want to avoid gets
. fgets
will always read the new-line if the buffer was big enough to hold it (which lets you know when the buffer was too small and there's more of the line waiting to be read). If you want something like fgets
that won't read the new-line (losing that indication of a too-small buffer) you can use fscanf
with a scan-set conversion like: "%N[^\n]", where the 'N' is replaced by the buffer size - 1.
One easy (if strange) way to remove the trailing new-line from a buffer after reading with fgets
is: strtok(buffer, "\n");
This isn't how strtok
is intended to be used, but I've used it this way more often than in the intended fashion (which I generally avoid).
Source: copied from my saved questions.