MPI C程序出现奇怪段错误:仅递增累加变量就崩溃问题求助
问题修复方案
崩溃根因定位
首先解释为什么看不到AFTER CUM SUM输出:
stdout默认使用行缓冲机制,你代码里
printf("AFTER CUM SUM");没有加换行符\n,输出内容会滞留在内存缓冲区中,程序崩溃后缓冲区未被刷新,所以看不到这行输出,不代表代码没有执行到这里。你给这行printf加上\n就能正常看到输出了。
从你提供的崩溃栈可以直接定位核心错误:
崩溃发生在fclose系统调用,错误地址为(nil),说明你给fclose传入了空指针。
你的代码中fclose(file)写在if分支的外侧:
- 只有
if(cum_sum > lowerbound && partition > 0)条件成立时,file才会被fopen赋值为有效的文件指针 - 如果条件不成立,
file是未初始化的野指针/空指针,直接传入fclose就会触发段错误。
其他潜在问题
- fopen未做返回值校验:就算进入if分支,
fopen也可能因为路径错误、权限不足、文件不存在等原因返回NULL,后续的fgetc、fclose调用传入空指针同样会崩溃。 - for循环遍历逻辑错误:你的
how_much_word数组共2个元素,循环条件tmp<sizeof(how_much_word)/sizeof(how_much_word[0])-1多减了1,只会遍历第一个元素,第二个元素永远不会被处理,不符合业务预期。 - 单词计数逻辑边界问题:如果文件最后一个字符是字母/数字,文件结束时不会触发单词计数逻辑,会漏掉最后一个单词。
修复后的代码参考
int arr_len = sizeof(how_much_word)/sizeof(how_much_word[0]); // 去掉多余的-1,遍历所有元素 for(int tmp=0; tmp < arr_len; tmp++){ cum_sum += how_much_word[tmp]; printf("Cumulative sum: %d \n", cum_sum); // 加换行符刷新缓冲区 printf("AFTER CUM SUM\n"); // 如果file是在循环外声明的,把下行改为file = NULL即可 FILE *file = NULL; if(cum_sum > lowerbound && partition > 0 ){ strcpy(path,"/myfolder"); strcat(path, file_name_and_number_words[tmp]); printf("name of file: %s \n", path); file = fopen(path, "r"); // 新增fopen返回值校验 if(file == NULL){ printf("Failed to open file: %s \n", path); // 打开失败直接跳过后续操作 continue; } printf("Opening the file: %s \n", file_name_and_number_words[tmp]); start = how_much_word[tmp] - (cum_sum - lowerbound); if (start < 0){ start = 0; } printf("Start reading: %d \n", cum_sum); in_word = 0; word_count = 0; while((ch = fgetc(file)) != EOF){ if(isalnum(ch) != 0 ){ in_word = 1; } else{ if ((ch == ' ' || ch == '\t' || ch== '\n') && (in_word == 1)){ word_count++; in_word = 0; if(word_count >= start){ partition--; } } } } // 补上文件末尾的单词计数 if(in_word == 1){ word_count++; if(word_count >= start){ partition--; } } printf("While is over with partition: %d\n", partition); } // 只有file非空的时候才调用fclose if(file != NULL){ fclose(file); } }
内容的提问来源于stack exchange,提问作者Gabriele Pisapia
相关产品推荐
相关产品推荐

