fscanf之后pclose时出现分段错误

时间:2019-11-28 14:49:22

标签: segmentation-fault scanf pclose

我尝试获取丢失的数据包编号(从树莓派上的ping命令),该编号用于路由器上的SIM卡交换。我尝试使用底部的代码(减少到引起错误的部分)来执行此操作,但是当我尝试释放(pclose)缓冲区时,出现了分段错误。我尝试了valgrind并得到了这个:

大小为4的读取无效 在0x490FBE0:fclose @@ GLIBC_2.4(iofclose.c:53) 地址0x382e3820未堆栈,未分配或(最近)未释放 进程以信号11(SIGSEGV)的默认操作终止 访问不在地址0x382E3820的映射区域内

我想我误用了fscanf,但是我不知道怎么做(我得到了printf结果,它是正确的-4)。

//remember to initialize final_boat_score first with all IDs you have
for (int i = 0; i < final_boat_score_size; i++) {
    //initialize the total point = 0 first
    final_boat_score[i].points = 0;
    //then loop through your input data
    for (int j = 0; j < boat_score_size; i++) {
        //if there exist an input element boat_score[j] with the same ID
        //as the current final_boat_score[i] element, add its points to the total
        if (final_boat_score[i].ID == boat_score[j].ID) {
            final_boat_score[i].points += boat_score[j].points;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题是这条线

fscanf(cmd, "%[^,], %d", &packetsReceived);

尝试将字符串读入int packetsReceived并运行为未定义行为,从而破坏了堆栈。您可能打算这样做

fscanf(cmd, "%*[^,], %d", &packetsReceived);