Search code examples
cstringstylesfgetscode-readability

What size should be used for fgets?


I have the following segment of code in one of my programs:

char input[LINE_SIZE + 1]; /* +1 for '\0'. */

while(fgets(input, LINE_SIZE, stdin) != NULL)
{
    /* Do stuff. */
}

In a question that has since been deleted, it was pointed out to me that my code could potentially be buggy. I declare strings with the "+ 1" notation to make the code more informative and readable (ensuring that I do not forget to account for the NULL terminator, because this used to be an issue). However, I have been told that the fgets should use the exact same size for its second parameter. I have seen other posts here that do the same practices as me.

I am unsure. Is it bad practice to not include the "+ 1" in the fgets parameter as well?


Solution

  • 7.21.7.2 The fgets function

    Synopsis

    1        #include <stdio.h>
             char *fgets(char * restrict s, int n, FILE * restrict stream);

    Description

    2     The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

    C 2011 Online Draft

    Emphasis added.

    If you specify LINE_SIZE, then fgets will read at most LINE_SIZE - 1 characters into input, and will write a 0 terminator following the last input character. Note that fgets will store the newline character if there's room.