Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does fgets() require a maximum size of user input? Is it because it does not have the "restrict to first space" property of scanf()?

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?

like image 448
Cccc Avatar asked Sep 14 '25 06:09

Cccc


1 Answers

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.

like image 165
wohlstad Avatar answered Sep 15 '25 21:09

wohlstad