1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #define TSIZE 45 5 6 struct film { 7 char title[TSIZE]; 8 int rating; 9 struct film *next; 10 }; 11 char * s_gets(char * st, int n); 12 13 int main(void) 14 { 15 struct film * head = NULL; 16 struct film * prev; 17 struct film * current; 18 char input[TSIZE]; 19 20 puts("Enter first movie title:"); 21 while(s_gets(input, TSIZE) != NULL && input[0] != '\0') 22 { 23 current = (struct film *) malloc(sizeof(struct film)); 24 if(head == NULL) 25 head = current; 26 else 27 prev->next = current; 28 current->next = NULL; 29 strcpy(current->title, input); 30 puts("Enter your rating <0-10>:"); 31 scanf("%d", ¤t->rating); 32 while(getchar() != '\n') 33 continue; 34 puts("Enter next movie title (empty line to stop):"); 35 prev = current; 36 } 37 38 if(head == NULL) 39 printf("No data entered. "); 40 else 41 printf("Here is the movie list:\n"); 42 current = head; 43 while(current != NULL) 44 { 45 printf("Movie: %s Rating: %d\n", 46 current->title, current->rating); 47 current = current->next; 48 } 49 50 current = head; 51 while(current != NULL) 52 { 53 current = head; 54 head = current->next; 55 free(current); 56 } 57 printf("Bye!\n"); 58 59 return 0; 60 } 61 62 char * s_gets(char * st, int n) 63 { 64 char * ret_val; 65 char * find; 66 67 ret_val = fgets(st, n, stdin); 68 if(ret_val) 69 { 70 find = strchr(st, '\n'); 71 if(find) 72 *find = '\0'; 73 else 74 while(getchar() != '\n') 75 continue; 76 } 77 78 return ret_val; 79 }
上面的代码来自《C Primer Plus》(第六版)中文版,第573-574页。
其中代码的第51行有错误。
不知道这个错误是印刷有错,还是原书有错。在此指出。
改正代码:
是将第51行的while(current != NULL)改为
while (head != NULL)就可以了。
原因如下:
将第51-56行代码之间添加一些输出,代码如下:
1 while(current != NULL) 2 { 3 printf("current1 = %p\n", current); 4 printf("head1 = %p\n\n",head); 5 current = head; 6 printf("current2 = %p\n", current); 7 printf("head2 = %p\n\n",head); 8 head = current->next; 9 printf("current3 = %p\n", current); 10 printf("head3 = %p\n\n",head); 11 free(current); 12 printf("current4 = %p\n", current); 13 printf("head4 = %p\n\n",head); 14 }
输出结果如下:
从上面的输出结果可以看出,最后一个head2指针已经是00000000了,是一个指向未知地址的指针。所以再次释放一个current就会出错。
改正后的输出: