1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 #include "mainc26.h" 5 struct TelPhone{ 6 char name[20]; 7 char TelNumber[20]; 8 struct TelPhone* next; 9 }; 10 int mainc26() 11 { 12 13 14 setbuf(stdout, NULL); 15 //fflush(stdout); 16 struct TelPhone *head = NULL; 17 struct TelPhone *pre,*current; 18 char input[20]; 19 printf("请输入联系人的姓名:\n"); 20 fflush(stdout); 21 while(gets(input) != NULL && input[0] != '\0') 22 { 23 current = (struct TelPhone*)malloc(sizeof(struct TelPhone)); 24 if(head == NULL) 25 head = current; 26 else 27 pre->next = current; 28 current->next = NULL; 29 strcpy(current->name,input); 30 printf("请输入联系人的电话号码:\n"); 31 scanf("%s",current->TelNumber); 32 while(getchar() != '\n') 33 continue; 34 printf("请输入下一个联系人(空行则退出):\n"); 35 pre = current; 36 } 37 if(head == NULL) 38 printf("电话里面没有储存任何数据:"); 39 else 40 puts("通讯录:"); 41 current = head; 42 while(current != NULL) 43 { 44 printf("%s:%s\n",current->name,current->TelNumber); 45 current = current->next; 46 } 47 current = head; 48 int n=0; 49 while(current != NULL) 50 { 51 n++; 52 printf("this is %d time \n",n); 53 free(current); 54 current=NULL; 55 printf("cur.name %s ,",current->name); 56 printf("cur.teln %s ,",current->TelNumber); 57 // printf("cur.name %p ,",current->next); 58 printf("\n"); 59 current = current->next; 60 } 61 return 0; 62 }
在 line 53中 使用free(current) ,这里似乎是将current的内存释放,然后实际上,这里的释放后,其内存信息已经存在,
如果将line 54的current=null,注释,该程序仍能正确运行,并通过该链表将内存释放掉,而实际上这种问题时错误的。
通过百度,我查到
问题如下:
1 代码如下: 2 #include <stdio.h> 3 #include <stdlib.h> 4 5 struct test 6 { 7 int a; 8 struct test *next; 9 }; 10 int main() 11 { 12 struct test test0={10}; 13 struct test *test1 = (struct test *)malloc(sizeof(struct test)); 14 test1->a=20; 15 test1->next = &test0; 16 free(test1); 17 printf("%d %d",test1->a,(*test1->next).a); 18 19 } 20 输出test1->a为0 ,(*test1->next).a为10 21 22 说明结构体里的变量a已经被free释放掉了,而test1的指针next却还可以被访问