从c中的双链表中删除元素

时间:2017-03-15 22:27:18

标签: c arrays list malloc

我有一个双链表,这是我用过的结构:

struct list_el{
    struct data* val;
    struct list_el* next;
    struct list_el* prev;
};

struct list{
    struct list_el* head;
    struct list_el* tail;
};

当我这样做时,一切正常,插入和删除功能正常工作:

int main(){
    struct data d1 = {"Name1","Surname1"};
    struct data d2 = {"Name2","Surname2"};
    struct data d3 = {"Name3","Surname3"};
    struct data d4 = {"Name4","Surname4"};
    struct list *l = create();
    struct list_el *el1, *el2, *el3, *el4;
    el1 = create_elem(&d1);
    el2 = create_elem(&d2);
    el3 = create_elem(&d3);
    el4 = create_elem(&d4);
    insert (l, el1);
    insert (l, el2);
    insert (l, el3);
    insert (l, el4);
    del_el(l, el1);
}

问题在于我想在数组上执行此操作:

struct data arr_data[4]={{"Name1","Surname1"},{"Name2","Surname2"},{"Name3","Surname3"},{"Name4","Surname4"}};

struct list_el arr_el[4];

int main(){    
    struct list *l = create_l();
    for (int i=0; i<4; i++) {
         arr_el[i] = *create_elem(&arr_data[i]);
         insert_l(l, &arr_el[i]);
    }   
    //Till now everythink works correctly

    //Here's the problem
    del_el(l, &arr_el[0]);
}

当我运行它时,它显示一个错误:

malloc: *** error for object 0x10002dfb0: pointer being freed was not allocated

不知道为什么会这样。在create_elem()我使用malloc。有任何想法吗?

1 个答案:

答案 0 :(得分:2)

您正试图释放arr_el的其中一个元素。由malloc分配的,因此您无法释放它们。

您正在做的是取消引用create_elem返回的指针,并将复制它包含的值放入arr_el元素中。这也意味着你有内存泄漏。

您应该将arr_el声明为指针数组

struct list_el *arr_el[4];

然后将create_elem的返回值直接分配给其中一个:

arr_el[i] = create_elem(&arr_data[i]);
insert_l(l, arr_el[i]);

然后您可以随后将其删除:

del_el(l, arr_el[0]);