1

I'm not too sure why this code causes segfault. I'm trying to find out how many words does a sentence contain. Can anyone help me resolve this?

#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;
}
stackyyflow
  • 767
  • 3
  • 11
  • 30

1 Answers1

1

You didn't check whether word was null before you called strcpy on it.

Also, your loop condition, sentence != NULL, will never be false. sentence isn't reassigned to anything that could be null. Perhaps you should be testing word != NULL?

C. K. Young
  • 219,335
  • 46
  • 382
  • 435