C Primer Plus(第六版)中文版 中的错误1
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 }View Code
上面的代码来自《C Primer Plus》(第六版)中文版,第573-574页。
其中代码的第51行有错误。
不知道这个错误是印刷有错,还是原书有错。在此指出。
改正代码:
是将第51行的while(current != NULL)改为
while (head != NULL)就可以了。
原因如下:
将第51-56行代码之间添加一些输出,代码如下:
while(current != NULL) { printf("current1 = %p\n", current); printf("head1 = %p\n\n",head); current = head; printf("current2 = %p\n", current); printf("head2 = %p\n\n",head); head = current->next; printf("current3 = %p\n", current); printf("head3 = %p\n\n",head); free(current); printf("current4 = %p\n", current); printf("head4 = %p\n\n",head); }View Code
输出结果如下:
从上面的输出结果可以看出,最后一个head2指针已经是00000000了,是一个指向未知地址的指针。所以再次释放一个current就会出错。
改正后的输出:
相关推荐
YFCEMBEDD 2019-06-21
MySQLLelove 2019-06-20
lcjwxd 2018-08-03
valecalida 2013-04-13
maleibo 2016-01-29
wyywn 2012-07-12
MySQLHD 2019-04-10