cstringstdinfgetsnull-character

fgets - Take null character into account


When scanning for user input using int scanf(const char *format, ...), I would read one less character than the string's size, because the last character of the string has to be the null character \0.

char str[10];
scanf("%9s", str); /* take \0 into account */

But when I use char *fgets(char *str, int n, FILE *stream), I don't know how I should specify n. Most online tutorials set it to sizeof(str), but someone told me that it should be sizeof(str) - 1.

So how would I prevent a buffer overflow? Like this:

char str[10];
fgets(str, 10, stdin);

Or should I do this:

char str[10];
fgets(str, 9, stdin);

Solution

  • See C11 7.21.7.2 (emphasis mine):

    1. The fgets function reads at most one less than the number of characters specified by n [...] A null character is written immediately after the last character read into the array.
    2. [if an error occurs] a null pointer is returned.

    So, the proper usage is using the full size of the array and check the return value.

    char buf[100];
    if (fgets(buf, sizeof buf, stdin) == NULL) /* all bets are off */;