我有一个双链表,这是我使用的结构:
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
.有什么想法吗?
您正在尝试释放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]);