c - 使用链表时 malloc 中的分段错误



程序从文件中读取,将所需的数据存储在某些变量中,然后将其推送到堆栈。这是输入文件的一小部分,该文件包含重复多次的数据(每个数据块中更改的变量值(。

----------------------------------------------------------------------- 
Timestamp (Wed Mar 29 20:44:08 2017) 
[1] Received msg from node <00116 / fc:c2:3d:00:00:10:ab:35> 
RSSI -6 dBm / LQI 22
+[Node_Voltage]  <2.963000 Volts> 
+[P_MS5637]      <896 mbar> 
+[NTC_THERM (Murata NXFT15XH103)]    <27.755314 deg C> 
+[Temp_LM75B]    <27.620001 Deg C> 
+[RH_CC2D33S]    <33.000000 %> 
+[Temp_CC2D33S]  <27.000000 Deg C> 

存储的数据被推送到发生分段错误的堆栈。发生故障后,该程序只能存储一个堆栈。

void create(stack **head){
    *head=NULL;
}
void copy_string(char arr[],char arr2[]){
    int i=0;
    for(i=0;i<strlen(arr2);i++){
        arr[i] = arr2[i];
    }
}
stack demo;          
stack *tracker;
// **head is used since this is an ADT, i've not pasted the code in source file here 
void push(stack **head,char date[],char time[],char month[],char year[],float pressure,float temprature1,float temprature2,float rel_humid,float node_voltage){
    stack *temp = malloc(sizeof(demo));   
    temp->pressure = pressure;
    temp->temprature1 = temprature1;
    temp->temprature2 = temprature2;
    temp->rel_humid = rel_humid;
    temp->node_voltage = node_voltage;
    printf("Inside push functionn");
    copy_string(temp->date, date);
    copy_string(temp->time, time);
    copy_string(temp->month, month);
    copy_string(temp->year, year);

    if(*head==NULL){
        temp->next = NULL;
        *head = temp;
        tracker = temp;
    }
    else{
        tracker->next = temp;
        tracker = tracker->next;
        tracker->next = NULL;
    }
    free(temp);     //on removing this, program runs infinitely instead of giving segmentation fault
    printf("%s %s %f %f ",tracker->date,tracker->year,tracker->pressure,tracker->node_voltage);
}

使用 gdb( GNU 调试器 ( 我收到此错误消息 -

Inside push function
29 2017) 896.000000 2.963000 Done!!
Program received signal SIGSEGV, Segmentation fault.
__GI___libc_free (mem=0x11f1) at malloc.c:2949
2949    malloc.c: No such file or directory.

解决:整个问题的原因是free(temp(,需要从上面的代码中删除它,并且在主文件中,文件指针在运行代码一次后被错误地关闭,因此无限循环在再次输入时运行。

您正在free()然后在*head==NULL时访问同一对象。查看下面标记为****的行。

if(*head==NULL){
    temp->next = NULL;
    *head = temp;
    tracker = temp;//**** temp is assigned to tracker. They point to the same place.
}
else{
    //...
}
free(temp);     //**** temp is free()d but remember tracker==temp..
//**** Now you output tracker but the object at this location was just freed.
printf("%s %s %f %f ",tracker->date,tracker->year,tracker->pressure,tracker->node_voltage);

因此,删除free(temp)它在完全错误的地方,但您没有提供足够的代码来说明它的去向。

"无限循环"是其他一些错误,但您没有提供足够的代码来识别它。

另请注意,else部分没有多大意义:

    tracker->next = temp;
    tracker = tracker->next;
    tracker->next = NULL;

目前尚不清楚tracker正在进入什么,但假设它是有效的,这相当于:

    tracker = temp;
    temp->next = NULL;

相关内容

  • 没有找到相关文章

最新更新