0
Help me with gets and fgets
What's the difference between "fgets(str, sizeof str, stdin);" and "gets(str)" ? I think both have the same function. Thank you already
5 Réponses
+ 4
as u can see, with fgets we can specify the number of bytes we want to write..fgets also stop when it encounters eof but not gets
using gets may cause buffer overfow
+ 3
Rishi there will be no problem till the time the input is within limits of buffer ( arr in this case )
The problem occurs when it reads a string greater than size of your buffer.
gets() only know from where to start writing in memory ( starting on the buffer ) and doesn't know when to stop, causing(as Lily Mea mentioned ) buffer overflow if huge input is provided.
Whereas fgets() does know when to stop ( provided as argument ) and will not write beyond the limit of your buffer, making it much safer alternative.
+ 1
Martin Taylor oh okay sure. Thank you
0
Lily Mea yeah but I don't quite understand it. Here, how does sizeof() function work for a string that is entered? And anyway both are going to stop after the end of the sentence that we entered. So what's the difference?