关于链表free的问题,感兴趣的过来看看!
代码相当简单,创建一个链表,再free,但是free后发现一个问题,当我再打印这个链表时,会发现
链表头不为NULL,而且出现了内存的非法访问,输出任意值。
难道说,我释放完链表的内存空间后,那片内存就填充了另外的值??
- C/C++ code
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <windows.h>typedef struct Student{ int num; int age; struct Student *next;}STU;STU *creat(int n);void printf_all(STU *pb);void link_free(STU *head);int main(){ STU *head=NULL; int n; printf("input num you want creat node\n"); scanf("%d",&n); head=creat(n); //创建n个结点 printf_all(head); printf("we will free link\n"); link_free(head); Sleep(100); if(head==NULL) //困惑? head!=NULL? { printf("***********\n"); } printf_all(head); //有错误,并有打印,为任意值 return 0;}STU *creat(int n){ STU *head,*pf,*pb; int i; for (i=0;i<n;i++) { pb=(STU *)malloc(sizeof(STU)); printf("input num age \n"); scanf("%d%d",&pb->num,&pb->age); if (i==0) { head=pf=pb; //当是头时,让指针均指向头 } else { pf->next=pb; //后面结点时,让前向指针的next指向当前结点,再把前向指针后移一下 pf=pb; } } pb->next=NULL; return head;}void printf_all(STU *pb){ STU *head=pb; while (head!=NULL) { printf("num=%d age=%d\n",head->num,head->age); head=head->next; } if(pb==NULL) { printf("the list is null.\n"); }}/*---------------------------------------------------链表释放---------------------------------------------------*/void link_free(STU *head){ STU *pb; pb=head; while(head!=NULL) { pb=head; head=head->next; free(pb); } if(head==NULL) { head = NULL; //加上这句,发现也没用,是不是应该需要返回 printf("comein\n"); //有打印 }}[解决办法]
本来就是这样 你都free掉了 判断NULL有什么用? 只能瞎指
[解决办法]
STU link_free(STU *&head)
这样改就行了
[解决办法]