读书人

这个链表程序老是出错啊错在哪儿啊该

发布时间: 2012-03-18 13:55:39 作者: rapoo

这个链表程序,老是出错啊,错在哪儿啊?
按照本意,它应该打印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应及时写在后面,这是个好习惯~

读书人网 >C语言

热点推荐