这段程序,请大家留意一下第37-42行(已经用红色字指出),再运行一下,就会看到问题了~~~我用free()来释放*p1所指的空间,可是居然会牵连到相邻的空间的数据:
struct student *del(struct student *head, int num) { struct student *p1,*p2=head; if(!head) printf("\nlist null!\n"); else { p1=head; while((p1->info!=num)&&p1->link!=NULL) { p2=p1; p1=p1->link; } if(p1->info==num) {
if(p1==head) { printf("p1==head\n"); head=p1->link; free(p1); } else { p2->link=p1->link; printf("line 37: head->info=%-6d head=%-6d head->link=%-6d &head->link=%-6d\n",head->info,head,head->link,&head->link); /*检查此时指针head的各项参数*/ printf("line 38: p2->info =%-6d p2 =%-6d p2->link =%-6d &p2->link =%-6d\n",p2->info,p2,p2->link,&p2->link); /*检查此时指针 p2 的各项参数*/ printf("line 39: p1->info =%-6d p1 =%-6d p1->link =%-6d &p1->link =%-6d\n",p1->info,p1,p1->link,&p1->link); /*检查此时指针 p1 的各项参数*/ free(p1); printf("line 41: p2->info =%-6d p2 =%-6d p2->link =%-6d &p2->link =%-6d\n",p2->info,p2,p2->link,&p2->link); /*检查此时指针 p2 的各项参数*/ printf("line 42: head->info=%-6d head=%-6d head->link=%-6d &head->link=%-6d\n",head->info,head,head->link,&head->link); /*检查此时指针head的各项参数*/ getch(); } printf("delete:%d\n",num); } else printf("%d not been found!\n",num); }
return (head); }
struct student *cre(struct student *head,int n) { int i; struct student *p;
if(n>0) {if(!head) { head=(struct student *)calloc(n,SIZE); p=head; } else { p=head; while(p->link)p=p->link; p->link=(struct student *)calloc(n,SIZE); p=p->link; }
printf("Insert %d datas:\n",n); for(i=1;i<=n;i++) { p->info=i; printf("line 75: p=%d p->info=%d",p,p->info); if(n-i) { p->link=(p+1); p=p->link; } else p->link=0; }} return head; } main() { ST *p,*p1=0; int i;
printf("Insert the amount of records:"); scanf("%d",&i); p1=cre(p1,i);
p=p1; while(p) { printf("line 98: p->info =%-6d p =%-6d p->link =%-6d &p->link =%-6d\n",p->info,p,p->link,&p->link); p=p->link; } getch();
printf("Insert the num you want to del:"); scanf("%d",&i); p1=del(p1,i);
p=p1; while(p) { printf("line 110: p->info =%-6d p =%-6d p->link =%-6d &p->link =%-6d\n",p->info,p,p->link,&p->link); p=p->link; } getch(); }