K&R第二版中的错误?

tim*_*geb 2 c bounds

这对我来说是一个看起来像虫子的东西,但是我很困惑,考虑到这本书的年龄和受欢迎程度,我的观察结果似乎没有出现在互联网上的任何其他地方.或者也许我只是在搜索时很糟糕,或者根本不是一个错误.

我在谈论第一章中"打印出最长输入线"的程序.这是代码:

#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */

int getline(char line[], int maxline);
void copy(char to[], char from[]);

/* print the longest input line */
main()
{
    int len; /* current line length */
    int max; /* maximum length seen so far */
    char line[MAXLINE]; /* current input line */
    char longest[MAXLINE]; /* longest line saved here */

    max = 0;
    while ((len = getline(line, MAXLINE)) > 0)
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    if (max > 0) /* there was a line */
        printf("%s", longest);
    return 0;
}

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

 /* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
    int i;
    i = 0;
    while ((to[i] = from[i]) != '\0')
        ++i;
} 
Run Code Online (Sandbox Code Playgroud)

现在,在我看来,它应该与getline的条件lim-2相反lim-1.否则,当输入完全是最大长度时,即999个字符后跟'\n',getline将索引到s[MAXLINE],这是超出范围的,并且当调用copy并且from[]不以a结尾时可能发生各种可怕的事情'\0'.

Car*_*rum 8

我觉得你在某个地方很困惑.这个循环条件:

for (i=0; i < lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
Run Code Online (Sandbox Code Playgroud)

确保i永远不会大于lim - 2,因此在最大长度的情况下,ilim-1在循环退出并且空字符存储到最后位置之后.