0

嗨,这是关于 Kernighan 和 Ritchie 关键字计数程序的问题(ANSI 版的第 6 章第 3 节)。我在下面的链接中包含了整个代码。

当我尝试在任何 C 源代码上运行代码时,我没有得到任何输出。因此,为了查明问题,我在代码的不同点打印了语句。终端窗口中程序的输出(应用到自身时)现在看起来像这样:

./a.out < keywords.c
I've got past the beginning of the getword loop.
I've got past the beginning of the getword loop.
I'm past the word[0] condition.
Segmentation fault

当我使用另一种搜索方法(通过结构键数组进行线性搜索)时,我得到了相同输出的另一种组合,这次没有分段错误。根据 printf 语句的输出,我倾向于认为 getword 函数有问题。那么是什么导致了这些错误呢?

以下是具有二进制和线性搜索功能的完整代码:

http://pastebin.com/sPEYYge6

4

2 回答 2

4

您的代码调用binsearch()并尝试使用mid该数组来访问该数组tab,但mid从未初始化,因此您将死在那里。

int binsearch (char * word, struct key tab[], int n) {
    int cond;
    int low, high, mid; 

    low = 0;
    high = n -1;
        // Missing setting mid here!    

    while (low <= high) {
        if ((cond = strcmp(word,tab[mid].word)) < 0) // That's going to be bad...
于 2012-12-04T15:57:04.280 回答
1

Mike 正确诊断出分段错误是由使用未初始化mid的 in引起的binsearch

您的代码中的其他错误(我不是 100% 确定我发现了所有错误)是:

  • getch()错了,return (bufp > 0) ? BUFF[bufp--] : getchar();返回 index 处的字符bufp,如果是> 0,但是bufp是存储在缓冲区中的元素数,应该在--bufp那里。
  • ungetch,测试if (bufp > BUFFSIZE)应该使用>=

您从未找到任何关键字的原因是(使用更传统的缩进和间距):

// You loop until you find a non-space character
while (isspace(c = getch())) {
    ;
}
// If it's not a letter, this is not a word, return here
if (!isalpha(c)) {
    *w = '\0';
    return c;
}
// If it was a letter, read the following letters and store them in the buffer
for ( ; --lim > 0; w++) {
    if (!isalnum(*w = getch())) {
        ungetch(*w);
        break;
    }
}

你永远不会存储任何单词的第一个字母,所以遇到 时volatile,只会olatile存储在缓冲区中。

只需在and循环*w++ = c;之间添加即可修复它,您的程序就可以正常工作(同时也进行了and修复)。ifforgetchungetch

于 2012-12-04T17:02:39.560 回答