我有这个函数来删除某个节点,然后循环它,直到所有具有该值的节点都从列表中删除。
然而,当我试图删除第一个节点时,它会在第二次调用时导致分段错误。它适用于列表的其他部分。
这是我调用的删除节点的函数:
int delete(char* value, char* attribute, int attr_count){
dataContainer = datadata;
dataList *temp, *prev;
temp = dataContainer;
prev = NULL;
int g = 0;
while(g < attr_count){
if(strlen(dataContainer->attributes[g]) == 0){
break;
}
if(!(strcmp(attribute, dataContainer->attributes[g]))){
break;
}
g++;
}
while(temp){
if(!(strcmp(temp->values[g], value))){
if(prev == NULL) {
dataContainer = temp->prev;
}else{
prev->prev = temp->prev;
}
free(temp);
return 1;
}
temp = dataContainer;
prev = temp;
temp = temp->prev;
}
return 0;
}
您可以在评论中看到我的解释:
在第二次调用任何东西的datadata点时,因为tmp在删除tmp时被释放,所以您应该更新datadata,如下datadata=tmp->next
while(temp){
if(!(strcmp(temp->values[g], value))){
if(prev == NULL) {
//when dataContainer->prev == NULL - you are in the head
dataContainer = temp->prev;
// if prev means previous in this case:
// dataContainer = NULL, on the second call segmentation fault appears when calling starting from line dataContainer->attributes[g]
}else{
prev->prev = temp->prev;
}