Is there a mistake in the code example in chapter 1.9 in the classic book C Programming Language?

In chapter 1.9, in the classic book on the C language "C programming language" by Brian and Dennis, there is a bunch of code about the "getline" function, which is used to copy the next line of input text to char, enter the line and check the overflow. I quote the code below:

int getline(char line[], int maxline);
int getline(char s[], int limit)
{
    int c,i;
    for (i=0; i<limit-1 && (c=getchar())!=EOF && c!='\n'; ++i) /* ** */
        s[i]=c;
    if (c == '\n') {
        s[i]=c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

Here's the problem: the "limit" parameter is the maximum length of the string, so the s [] array can only contain a set of elements from s [0] to s [limit-1]. If the last character for the variable c for getchar () is '\ n', and this character index is limit-1, then part of the judgment in the 'for' loop will fail due to 'i == limit-1', but not 'c! = '\ n' (according to the sequence from left to right). Further, if the sentence will work, because of 'c ==' \ n '', then s [limit-1] = c, then ++ I will set the value I to the limit. s [i] = '\ 0' will overflow because s [limit] will exceed the line limit. Is my analysis correct or not? Thanks for the helpful answers.

+4
2

. i == limit-1, c - . , if (c == '\n'). i limit-1 .

: " i , limit-1, , EOF , ". , i - limit-1, .

+4

. .

for (i=0; i<limit-1 && (c=getchar())!=EOF && c!='\n'; ++i)
//        (   A   )    (        B        )   (  C  )

&&. , . :

  • A , , B, C.
  • , B , C .
  • C , false.

...

  • i<limit-1 , getchar(), EOF, '\n'.
  • else if (c=getchar())!=EOF false, '\n' .
  • '\n'.

, .

+3

All Articles