Falha de segmentação (núcleo despejado) lida de stdin
Eu estou tentando contar o número de cada palavra em um arquivo. O arquivo pode ser stdin ou um nome de arquivo fornecido na linha de comando (./ count -f). Até agora, o programa fornece as saídas corretas ao ler um arquivo da linha de comando. Mas um erro acontece quando eu estou tentando ler de stdin. O programa primeiro gera o valor correto e, em seguida, fornece uma falha de segmentação (núcleo despejado). Aqui faz parte do meu código.
FILE * fp;
int size = 20000;
char sentence[2000]; // the sentence from stdin
if ( argc != 3 )
{
fgets(sentence,sizeof(sentence),stdin); // read from stdin
fflush(stdin);
// I think the initialization of word is incorrect, but i do know why it is incorrect
char *word = strtok (sentence," !\"#$%&'()*+,./:;<=>?@[\\]^_`{|}~\n\t");
while (word != NULL)
{
get_word(word); // get each word
word = strtok (NULL, " !\"#$%&'()*+,./:;<=>?@[\\]^_`{|}~\n\t");
}
}
else
{
fp = fopen( argv[2], "r" );
if ( fp == 0 )
{
printf( "Could not open file\n" );
}
char word[1000];
while (readFile(fp, word, size)) { // let the program read the file
get_word(word); // get each word. Works well.
}
}
função get_word:
void get_word(char *word){
node *ptr = NULL;
node *last = NULL;
if(first == NULL){
first = add_to_list(word); // add to linked list
return;
}
ptr = first;
while(ptr != NULL){
if(strcmp(word, ptr->str) == 0){
++ptr->freq;
return;
}
last = ptr;
ptr = ptr->next;
}
last->next = add_to_list(word); // add to linked list
}
Por favor me ajude a descobrir porque eu recebo uma falha de segmentação (core dumping). O programa funciona no meu mac, mas não funciona no Linux.
Desde já, obrigado.