而循环分段故障

时间:2013-03-30 01:57:22

标签: 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函数在其他文件中正常工作;

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;
}

1 个答案:

答案 0 :(得分:0)

首先,你的for循环结束时i的值比单词的长度多一个,所以这是不正确的:

word[i+1]='\0'

应该是:

word[i]='\0'

其他几条评论:

  • 使用isalpha(c)
  • 将malloc / strcpy折叠为strdup
  • write end == 0&amp;&amp; word!= NULL as(end == 0)&amp;&amp; (字!= NULL)