我正在尝试计算文件中每个字的数量。该文件可以是stdin或命令行中提供的文件名(./ count -f)。到目前为止,程序在从命令行读取文件时会提供正确的输出。但是当我试图从标准输入读取时发生错误。程序首先输出正确,然后给出分段错误(核心转储)。这是我的代码的一部分。从标准输入读取的分段错误(核心转储)
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," !\"#$%&'()*+,./:;<=>[email protected][\\]^_`{|}~\n\t");
while (word != NULL)
{
get_word(word); // get each word
word = strtok (NULL, " !\"#$%&'()*+,./:;<=>[email protected][\\]^_`{|}~\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.
}
}
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
}
请帮我弄清楚,为什么我得到一个分段错误(核心转储)。该程序适用于我的Mac,但不适用于Linux。
在此先感谢。
'fflush(stdin)'触发未定义的行为。 get_word是做什么的? – cnicutar 2013-04-09 19:07:20
这不是根本原因,但你不应该调用'fflush(stdin);' - 输入流中未定义fflush。 – Joe 2013-04-09 19:07:49
不,它不是fflush(stdin)问题。我删除它,但仍然得到错误。我认为这是一个记忆问题。该程序适用于我的Mac,但不适用于Linux。 – user605947 2013-04-09 19:11:22