Reputation: 73
I have a double linked list, here's structure I used:
struct list_el{
struct data* val;
struct list_el* next;
struct list_el* prev;
};
struct list{
struct list_el* head;
struct list_el* tail;
};
When I do it like this, everything works correctly, insert and delete functions are working as I wanted:
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);
}
The problem is when I want to do it on arrays:
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]);
}
When I run it it shows me an error:
malloc: *** error for object 0x10002dfb0: pointer being freed was not allocated
Don't know why it happened. In create_elem()
I use malloc
. Any ideas?
Upvotes: 0
Views: 61
Reputation: 224927
You're trying to free one of the elements of arr_el
. These were not allocated by malloc
, so you can't free them.
What you're doing is dereferencing the pointer returned by create_elem
and copying the values it contains into an element of arr_el
. This also means you have a memory leak.
You should instead declare arr_el
as an array of pointers:
struct list_el *arr_el[4];
Then you assign the return value of create_elem
directly to one of these:
arr_el[i] = create_elem(&arr_data[i]);
insert_l(l, arr_el[i]);
And you can then subsequently delete them:
del_el(l, arr_el[0]);
Upvotes: 2