I know, that using gets() is a very bad idea as it may lead to buffer overflow. But I have some queries.
Suppose a c program has the following code-
char word[6];
gets(word);
puts(word);
If I input for example -
HELLO WORLD
, is it correct to assume that gets()
reads it as [H] [E] [L] [L] [O] [ ]
, and the rest goes into the input buffer ?
If that happens than, how does puts()
get the data to display the complete string ?
Your question suggests you think gets
might somehow know that word
is only 6 characters long, so it fills it with just 6 characters and leaves the rest in the buffer associated with the input stream. That is not the case. The call gets(word)
passes only the start address of word
to gets
. That is all it receives—a starting location. It does not receive any information about length. gets
reads from the input stream until a new-line character is read or an end-of-file is encountered or an error occurs.
If you entered “HELLO WORLD”, and the program printed that, it is because gets
read the data and wrote it into memory, exceeding the bounds of word
. There is not any fancy buffering or interaction occurring—gets just wrote over memory that was not assigned for that purpose. It could have broken something in your program. But it appears you got “lucky” in that the error did not immediately break your program, and the data sat there until puts
could read it from memory and write it to output.
However, you should never expect that behavior. One reason that worked the way it did is you have a very simple program that did not do anything else with memory. In more complicated programs, where there are many objects and activities, it is more likely that overrunning a buffer will break the program in a variety of ways.