这个链表程序,老是出错啊错在哪儿啊该怎么处理
这个链表程序,老是出错啊,错在哪儿啊?
按照本意,它应该打印2次 0 1 2 3 4 5 6,思路是分配一个链表,然后free释放掉,然后重新再分配一次,再释放掉,2次动作一样,可是老是说什么内存冲突,帮忙看看
------解决方案--------------------
按照本意,它应该打印2次 0 1 2 3 4 5 6,思路是分配一个链表,然后free释放掉,然后重新再分配一次,再释放掉,2次动作一样,可是老是说什么内存冲突,帮忙看看
- C/C++ code
#include <stdio.h> void getfree(struct data *); //释放内存函数 void print(struct data *); //打印函数 void list(struct data *); //分配链表函数 struct data{ int num; struct data* next; }; int main(){ struct data *head,*tail,*temp; int i; head=(struct data*)malloc(sizeof(struct data)); tail=head; list(tail); temp=head; print(temp); temp=head; getfree(temp);//释放链表 //重新分配链表并且打印,重复做一次上面的动作 tail=head; list(tail); temp=head; print(temp); temp=head; getfree(temp);//释放链表 system("pause"); return 0; } void getfree(struct data *head){ struct data *temp; do{ temp=head; head=head->next; free(temp); }while(head->next==NULL); free(head); } void print(struct data *head){ struct data *temp; do{ temp=head; head=head->next; printf("%d ",temp->num); }while(head->next!=NULL); printf("%d",head->num); } void list(struct data *tail){ struct data *temp; int i; for(i=0;i!=6;++i){ temp=tail; tail->num=i; tail->next=(struct data*)malloc(sizeof(struct data)); tail=tail->next; tail->next=NULL; } tail->num=i; }
------解决方案--------------------
- C/C++ code
temp=head; //下面一句相当于吧head给free了,因为temp指向的是head getfree(temp);//释放链表 //加上下面这句,重新分配head head=(struct data*)malloc(sizeof(struct data));
------解决方案--------------------
1.缺乏头文件#include<stdlib.h>;
2.void getfree(struct data *head){
struct data *temp;
do{
temp=head;
head=head->next;
free(temp);
}while(head->next==NULL);//判断条件错误,应该是head->!=NULL
3.重复上述操作,头结点head应该重新分配空间,所以再用一次head=(struct data*)malloc(sizeof(struct data));
4.建议head分配空间成功,head->next=NULL应及时写在后面,这是个好习惯~