我正在尝试计算一个文件中每个单词的个数。该文件可以是标准输入,也可以是命令行上提供的文件名(./count -f )。到目前为止,程序在从命令行读取文件时给出了正确的输出。但是当我试图从stdin读取时,发生了一个错误。程序首先输出正确的,然后给出一个分段故障(核心转储)。以下是我的代码的一部分。
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.
}
}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上运行。
提前谢谢。
发布于 2013-04-10 04:03:58
问题是
int main (int argc, char *argv[]) {
FILE * fp;
if ( argc != 3 )
{
fgets(sentence,sizeof(sentence),stdin);
// and so on
}
else
{
fp = fopen( argv[2], "r" );
if ( fp == 0 )
{
printf( "Could not open file\n" );
}
while (readFile(fp, word, size)) {
get_word(word);
}
}
// do some stuff, sorting etc.
fclose(fp);无论它是否打开,您都可以使用fclose(fp)。如果fp未连接到有效的流,则通常会出现分段故障。显然,一些实现很好地处理了fclose的NULL参数,这就是它在Mac上看起来可以工作的原因。
将fclose调用移到else分支中,当fopen失败时,不要只是
printf( "Could not open file\n" );但是结束这个节目。
发布于 2013-04-10 03:10:57
句子大小为2 kib,您从stdin读取的是2 kib。在此之后,您可以在其上使用字符串函数。字符串以‘\0’结尾,但由于您读取的2 kib数据没有'\0',因此没有字符串结尾,因此它会分段,因为字符串函数(本例中为strtok)的工作范围可能远远超出了2 kin。
https://stackoverflow.com/questions/15910444
复制相似问题