| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 877 人关注过本帖
标题:清理链表的疑问?
取消只看楼主 加入收藏
TAAAAB
Rank: 7Rank: 7Rank: 7
来 自:湖南
等 级:黑侠
威 望:1
帖 子:243
专家分:635
注 册:2011-5-29
结帖率:95.24%
收藏
已结贴  问题点数:20 回复次数:2 
清理链表的疑问?
书本上的程序清单是不是印错了。
照书上的打出来运行出错,是不是错在最后一个循环中在已释放的内存中去读取值?

程序代码:
/* 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", &current->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;
}
搜索更多相关主题的帖子: 清理 
2015-04-08 11:30
TAAAAB
Rank: 7Rank: 7Rank: 7
来 自:湖南
等 级:黑侠
威 望:1
帖 子:243
专家分:635
注 册:2011-5-29
收藏
得分:0 
回复 3楼 TonyDeng
C Primer Plus(第五版) 的程序清单17.2

人有多懒,编程就有多难。
2015-04-08 14:08
TAAAAB
Rank: 7Rank: 7Rank: 7
来 自:湖南
等 级:黑侠
威 望:1
帖 子:243
专家分:635
注 册:2011-5-29
收藏
得分:0 
是不是要这样理解
这种做法依靠不同系统C的实现,总之是不可取的。因为不能保证释放后数据一定还在,如果刚好被其它程序用了呢。
这样写出现问题的时候虽然能马上知道问题所在(在自己能记得的前提下)但是更好的方法是要避免会出现问题。

人有多懒,编程就有多难。
2015-04-09 09:50
快速回复:清理链表的疑问?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.016150 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved