This is fgets()
's official prototype:
char *fgets(char *str, int n, FILE *stream);
Why specify the size (n
) ? Is it to prevent buffer overflow of some sort? Or is it just a design flaw?
I would think that it's caused by gets()
tendency to cause buffer overflow and segfault your program, but that's only my guess.
In any case, this may be related to the fact that fgets()
is a file function, but I would also have no idea.
This is in the context of a recent video on buffer overflow, and in a security context, is this a risk? Is the size a limitation, and in this context, prone to segfaulting?
From cppreference.com C documentation:
fgets
Reads at most count - 1 characters from the given file stream and stores them in the character array pointed to by str
...
count - maximum number of characters to write (typically the length of str)
(emphasis is mine)
count
is the size parameter named n
in your question.
According to the Linux manual page, fgets
should read at most n - 1
(i.e. count - 1
) bytes:
The fgets() function shall read bytes from stream into the array pointed to by s until n-1 bytes are read, or ...
So the bottom line:
fgets
reads at most n - 1
characters and writes them to str
. Since it adds a zero ('\0'
) termination, it will write at most n
bytes.
But anyway - basically, the answer is yes; it is for preventing a buffer overflow when filling str
(assuming you pass the proper size of str
).
It is definitely not a design flaw.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With