In Chapter 17 "advanced data representation" of the fifth edition of the book, the following code is provided in listing 17.2:
# Include <stdio. h> # include <stdlib. h> # include <string. h ># define tsize 45 # define Len sizeof (struct film) struct film {char title [tsize]; int rating; struct film * Next;}; int main () {struct film * head = NULL; struct film * Pre, * Current, * Hou; char input [tsize]; /* collect and store information */puts ("enter first movie title:"); While (gets (input )! = NULL & input [0]! = '\ 0') {current = (struct film *) malloc (LEN); If (Head = NULL) {head = current ;} else {pre-> next = current;} current-> next = NULL; strcpy (current-> title, input); puts ("Enter your rating <0-10>: "); scanf (" % d ", comment T-> rating); While (getchar ()! = '\ N') continue; puts ("Enter next movie title (empty line to stop):"); Pre = current ;} /* List movies */If (Head = NULL) {printf ("no data entered. ");} else {printf (" here is the movie list: \ n ");} current = head; while (current! = NULL) {printf ("movie: % s Rating: % d \ n", current-> title, current-> rating); current = Current-> next ;}/* The task is completed, so the allocated space is released */current = head; while (Head! = NULL) {free (current); current = Current-> next ;}Printf ("Bye! \ N "); Return 0 ;}
In VC ++ 6.0, assertion failure is triggered. After debugging, the problem is found in the last part, and "the task is completed. Therefore, the allocated memory space is released" (bold in this article ), after debugging, the following problems are found:
This part starts to point to head with current. In the while loop, first free (current). Since the current memory space has been released, how does one set current to current-> next? So assertion fails. You can use another Hou to save the pointer of the next node to be released.
/* The task has been completed, so release the allocated memory */current = head; Hou = Current-> next; while (Hou! = NULL) {printf ("here! \ N "); free (current); current = Hou; Hou = Current-> next;} Free (current );
C primer plus is indeed a great book, but it is better to believe in books than to have no book. The author Stephen Prata may also hope that his readers can find some minor mistakes that he may encounter inadvertently!
In addition, I verified my idea in program list 17.5 of the book. The author gave a function to clear the linked list. The basic idea is the same. The Code is as follows:
/* Release the memory allocated by malloc () * // set the list pointer to null */void emptythelist (list * plist) {node * psave; while (* plist! = NULL) {psave = (* plist)-> next; free (* plist); * plist = psave ;}}
Link: http://hi.baidu.com/mayadong7349/item/b88d0630a3d9043d2e20c4c2