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

时间:2017-06-19 08:01:03

标签: c linked-list stack 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 function\n");

    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),它需要从上面的代码中移除,并且在主文件中,文件指针在运行代码后被错误地关闭,因此无限循环运行同时再次接受输入。

1 个答案:

答案 0 :(得分:1)

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)它是在完全错误的地方,但你没有给出足够的代码来说明它的去向。

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

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

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

不清楚tracker的内容是什么,但假设它有效,则相当于:

    tracker = temp;
    temp->next = NULL;