I tried to free the linked list I created , but I failed.
An extension on the previous question I asked "Merge double linked list", it is OK if you don't check it or know nothing about it.
I created two double linked list, and I merged them, and after that, I want to free them all. So I wrote the delete_list() function.
But eventually, I failed, the error is "error for object 0x100404110: pointer being freed was not allocated".
If I only free the first list l, the code works. But if I tried to free all or two, the code crushed.
Can anyone help me with it? Thanks!!
#include <stdio.h>
#include<stdlib.h>
typedef struct Node
{
struct Node* prior;
struct Node* next;
int value;
}Node,*list;
list create_list()
{
list head = (list)malloc(sizeof(Node));
if(!head) exit(-1);
list tail;
tail=head;
printf("Please enter the length of double linked list:\n");
int len;
scanf("%d",&len);
for(int i=0;i<len;i++)
{
list new = (list)malloc(sizeof(Node));
if(!new) exit(-1);
new->next=NULL;
printf("Please enter the value of node:\n");
int val;
scanf("%d",&val);
new->value=val;
tail->next = new;
new->prior=tail;
tail=new;
}
return head;
}
list merge_list(list a,list b)//合并两个非递减双向链表
{
if(a==NULL||b==NULL) exit(-1);
list p=(list)malloc(sizeof(Node));
list l=p;
while(a&&b)
{
if(a->value<=b->value)
{
p->next = a;
a->prior=p;
p=a;
a=a->next;
}
else
{
p->next = b;
b->prior=p;
p=b;
b=b->next;
}
}
if(a!=NULL)
{
p->next=a;
a->prior=p;
}
if(b!=NULL)
{
p->next=b;
b->prior=p;
}
return l;
}
int delete_List(list l)
{
if(l==NULL)
{
printf("List is empty!");
exit(-1);
}
list temp;
while(l)
{
temp = l->next;
free(l);
l=NULL;
l=temp;
}
return 1;
}
int main() {
list l = create_list();
l=l->next;//throw away the empty node
list m = create_list();
m=m->next;//throw away the empty node
list n =merge_list(l,m);
n=n->next; //throw away the empty node
delete_List(l);
delete_List(m);
delete_List(n);
return 0;
}
NO error.