c - While循环段错误

标签 c while-loop segmentation-fault

我正在尝试编写一个程序,该程序从定向到 stdin 的文件中读取,然后找到文件中最常用的两个单词。我几乎一切都工作正常,但现在我的 while 循环出现了奇怪的段错误

char *word=readWord();
int end=0;
while(end==0&&word!=NULL){
    printf("word readn %s\n",word);
    list=addToList(list,word);
    printf("added to list\n");
    word=readWord();
    if(word==NULL){
        end=1;
        printf("word is null\n");
    }
}
printf("done while loop");

当使用包含字“一二三四”的文件运行时,输出如下。

word readn one
added to list
word readn two
added to list
word readn three
added to list
word readn four>
added to list
word is null
Segmentation fault

readWord function works fine in other files;

char * readWord(){

    //temporary char array to read string
    char c,word[BUFFER_SIZE];

    if(scanf("%c",&c)==EOF){
        return NULL;
    }
    while(!((c>='a'&&c<='z')||(c>='A'&&c<='Z'))){
        if(scanf("%c",&c)==EOF)
            return NULL;
    }
    int i;
    for( i=0;(c>='a'&&c<='z')||(c>='A'&&c<='Z');i++){
        word[i]=c;
        scanf("%c",&c);
    }
    word[i+1]='\0';

    //dynamic allocation of just enough memory to store the word
    char * str= malloc(strlen(word) +1);
    strcpy(str,word);
    return str;
}

最佳答案

第一件事是 for 循环末尾的 i 值比单词的长度大 1,所以这是不正确的:

word[i+1]='\0'

应该是:

word[i]='\0'

其他一些评论:

  • 使用 isalpha(c)
  • 将 malloc/strcpy 折叠为 strdup
  • 将 end==0&&word!=NULL 写为 (end == 0) && (word != NULL)

关于c - While循环段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15714072/

相关文章:

我可以得到一些关于 C 中这个 `isPalindrome()` 函数的反馈吗?

找不到错误 - 将文本添加到数据文件时未找到段落

javascript - 直到 localStorage.getItem 为 '1' - Javascript

c - 返回零后出现段错误

c++ - 为什么 string.insert(iterator,char) 连续工作六次而不是七次? (C++)

c - 使文件在所有节点上可用

c - execvp 出现段错误

php - while 循环在从表中选择多列时不起作用

python - 如何在 while 循环中省略 it.combinations() 的一些结果

c++ - 为什么节点不能链接在一起?