+ 11
scanf and gets in C
what is the major effect of using scanf to get a string value and why gets and fgets are better off
2 Respostas
+ 10
It's common we see people do scanf("%s", string_variable); but this is considered unsafe because we didn't specify maximum number of characters to be read in, causing more characters possibly be written into the buffer than the buffer size allowed. Although not entirely sure, I think it's pretty safe if we define the maximum number of characters to read into the buffer such as scanf("%49s", string_variable); assuming the buffer was allocated for 50 characters (minus one for string terminator).
IIRC, from what I read, also in SoloLearn sometimes before, `gets` is highly discouraged for the same reason, it doesn't even support buffer size definition (or was it deprecated?).
On the other hand, `fgets` is "smart" enough to know the buffer size. But there's one thing that's quite bothering (for me at least), that `fgets` includes the line feed character while writing in the buffer, so care need to be taken with that function, after function call, one would need to find the \n and replace it with \0.
Hth, cmiiw
+ 3
I have always preferred scanf to gets and fgets but it's good to know the drawbacks.