当前位置: 代码迷 >> C语言 >> [求助]又是关于free()函数的~~~
  详细解决方案

[求助]又是关于free()函数的~~~

热度:202   发布时间:2005-06-24 23:42:00.0
[求助]又是关于free()函数的~~~

这段程序,请大家留意一下第37-42行(已经用红色字指出),再运行一下,就会看到问题了~~~我用free()来释放*p1所指的空间,可是居然会牵连到相邻的空间的数据:

#include <stdio.h> #include <stdlib.h> #include <malloc.h> #define ST struct student #define SIZE sizeof(ST) struct student {int info; struct student *link; };

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(); }

搜索更多相关的解决方案: free  函数  

----------------解决方案--------------------------------------------------------
晕~~~~~~``
重复发贴`
你!!!!!!!!!!!
----------------解决方案--------------------------------------------------------
说明你根本就没有认真看我的贴啊!这个已经是我更正过后的程序了,已经把问题的所在标明出来了~~~帮帮忙啦~~~这位大哥~~~不要只是看~~~你运行一下就知道啦~~~那个free()函数会把*p1所指的区域以外的数据都影响了的啊!
----------------解决方案--------------------------------------------------------
自己顶
----------------解决方案--------------------------------------------------------