cc-stringsfgetsbuffer-overflow

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?


Solution

  • Why does fgets() require a maximum size of user input?

    To limit the amount of data that is saved - preventing buffer overflow cases.


    Why specify the size?

    To prevent fgets() from saving too many characters.

    It also stops reading characters.
    fgets() could have read excess characters in a line and not save them, yet the design is to read up to size - 1 characters and save them and then append a null character. If the buffer fills without a '\n', the rest of the line remains to be read.

    Is it to prevent buffer overflow of some sort?

    Yes, this prevents a buffer overflow. It also stops the reading of characters from the file.

    Or is it just a design flaw?

    It is by design as a limiting alternate to code like gets() (no longer parts of the C library) and scanf("%s", ... which remains risky.

    Other (and later) functions that specify the buffer size are of type size_t. fgets() with its int size is a minor design flaw.

    and in a security context, is this a risk?

    Passing in a limiting size reduces risk.

    Is the size a limitation, and in this context, prone to segfaulting?

    The size reduces segment faults.


    Reading a line in C is only partially handled by fgets().
    Issues remain (some are pedantic):

    C deserves a better readline function.