清理链表的疑问?
书本上的程序清单是不是印错了。照书上的打出来运行出错,是不是错在最后一个循环中在已释放的内存中去读取值?
程序代码:
/* films2.c -- 使用结构链表 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TSIZE 45
struct film {
char title[TSIZE];
int rating;
struct film * next;
};
int main(void)
{
struct film * head = NULL;
struct film * prev, *current;
char input[TSIZE];
puts("Enter first movie title: ");
while (gets(input) != NULL && input[0] != '\0')
{
current = (struct film *)malloc(sizeof(struct film));
if (head == NULL)
head = current;
else
prev->next = current;
current->next = NULL;
strcpy(current->title, input);
puts("Enter your rating <0-10>: ");
scanf("%d", ¤t->rating);
while (getchar() != '\n')
continue;
puts("Enter next movie title (empty line to stop): ");
prev = current;
}
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;
}
current = head;
while (current != NULL)
{
free(current); //这里已经将动态分配的内存释放了,例题为什么还能读current->next
current = current->next;
}
printf("Bye!\n");
return 0;
}









