我有这个函数用于删除某个节点,然后我循环它直到从列表中删除所有具有这样值的节点。
但是,当我尝试删除第一个节点时,它会导致第二次调用时出现分段错误。它适用于列表的其他部分。
这是我要调用的删除节点的函数:
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;
}
答案 0 :(得分:-1)
您可以在评论中看到我的解释:
在第二次调用数据点指向任何内容因为删除tmp时释放tmp,您应该更新数据元素,例如此datadata = tmp-&gt; 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;
}