2014-10-25 1 views
1

왜이 코드가 segfault를 발생시키는 지 잘 모르겠습니다. 나는 얼마나 많은 단어들이 문장을 포함하고 있는지 알아 내려고 노력하고있다. 누구든지이 문제를 해결할 수 있습니까?strtok을 사용하는 동안 segfault가 발생하는 strcpy

#include <stdio.h> 
#include <string.h> 
#include <ctype.h> 
#define MAX 1000 

int main(void){ 
    char sentence[MAX + 1] = {0}; 
    char *word; 
    int count, len, i, num = 0; 

    while(fgets(sentence, MAX, stdin)){ 
     num = 0; 
     word = sentence; 
     word = strtok(word, " "); 

     while(sentence != NULL){ 
      char separate[MAX + 1] = {0}; 
      count = 0; 
      word = strtok(NULL, " "); 

      strcpy(separate, word); 
      len = strlen(separate); 
      for(i = 0; i < len; i++) 
       if(isalpha(sentence[i])) 
        count++; 

      if(count == len || count == len - 1) 
       num++; 
     } 

     printf("%d\n", num); 
    } 
    return 0; 
} 

답변

1

당신은 당신이 그것에 strcpy라고하기 전에 word가 null 여부를 확인하지 않았다.

또한 루프 상태 인 sentence != NULL은 결코 거짓이 아닙니다. sentence은 null 일 수있는 모든 것으로 재 할당되지 않습니다. 아마도 word != NULL을 테스트해야할까요?

+0

감사합니다. :) 관리가 작동하도록하십시오! – stackyyflow

관련 문제