代码末尾对malloc()分配的内存内存进行释放,但加上这段代码后编译会出错,不释放反而可以。不说说凡是有malloc()都要free()吗?
#include<stdio.h> #include<string.h> #include<stdlib.h> #define TSIZE 45 struct film { char title[TSIZE]; int rating; struct film *next; /*指向链表的下一个结构*/ }; int main(void) { struct film * head = NULL; struct film * current, * prev; char input[TSIZE]; /*收集并存储信息*/ puts("enter the 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 the movie rating(0-10)"); scanf("%d", ¤t->rating); while (getchar() != "\n") { continue; } puts("enter the next movie title(enter empty line to quit):"); prev = current; } /*给出电影列表*/ if (head == NULL) { puts("no date entered!"); } else { printf("here is the movie list:"); } current = head; while (current != NULL) { printf("Movie: %s rating: %d", current->title, current->rating); current = current->next; } /*释放分配的内存*/ current = head; while (current != NULL) { free(current); current = current->next; } printf("Bye!"); return 0; }
解决方案
20
free(current);
current = current->next; // 前面一行已经释放了current,那么这里就不能再使用current->next了
应该是这样:
tmp = current->next;
free(current);
current = tmp;
current = current->next; // 前面一行已经释放了current,那么这里就不能再使用current->next了
应该是这样:
tmp = current->next;
free(current);
current = tmp;