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", &current->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行代碼之間添加一些輸出,代碼如下:

 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     }
View Code

輸出結果如下:

 

從上面的輸出結果可以看出,最后一個head2指針已經是00000000了,是一個指向未知地址的指針。所以再次釋放一個current就會出錯。

 改正后的輸出:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM