首页
Web开发
Windows程序
编程语言
数据库
移动开发
系统相关
微信
其他好文
会员
首页
>
其他好文
> 详细
《C Primer Plus 》动态链表删除的一个错误
时间:
2015-03-14 20:04:44
阅读:
215
评论:
0
收藏:
0
[点我收藏+]
标签:
《C Primer Plus》确实是一本伟大的书,但尽信书不如无书,作者Stephen Prata可能也希望他的读者能找到些许他在不经意中出现的小错误吧!
在该书第五版17章“高级数据表示”中,程序清单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];
/*
收集并存储信息
*/
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", ¤t->rating);
while(getchar()!=‘\n‘)
continue;
puts("Enter next movie title(empty line to stop):");
pre = 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(head != NULL)
{
free(current);
current = current->next;
}
printf("Bye!\n");
return 0;
}
在vc++6.0中会引发断言失败,调试后发现问题处在最后一部分,及“任务完成,因此释放所分配内存空间部分”(文中已加粗),经过调试后,发现问题如下:
此部分开始用current指向head,while循环中首先free(current),既然已经释放掉current内存空间,下一步如何让current指向current->next?所以出现断言失败。
修改方法:使用另外一个指向节点的指针hold,用来保存当前将要释放节点的下一个节点的指针。
/*
任务已完成,因此释放所分配的内存
*/
current = head;
while(current != NULL)
{
hold = current->next;
free(current);
current = hold;
}
补充:随后在该书的程序清单17.5中就验证了本人的想法,作者给出了一个清空链表的函数,基本想法一致,代码如下:
/*
释放由
malloc()
分配的内存
*/
/*
把列表指针置为
NULL*/
void EmptyTheList(List *plist)
{
Node* psave;
while(*plist != NULL)
{
psave = (*plist)->next;
free(*plist);
*plist = psave;
}
}
《C Primer Plus 》动态链表删除的一个错误
标签:
原文地址:http://blog.csdn.net/luopingfeng/article/details/44262601
踩
(
0
)
赞
(
0
)
举报
评论
一句话评论(
0
)
登录后才能评论!
分享档案
更多>
2021年07月29日 (22)
2021年07月28日 (40)
2021年07月27日 (32)
2021年07月26日 (79)
2021年07月23日 (29)
2021年07月22日 (30)
2021年07月21日 (42)
2021年07月20日 (16)
2021年07月19日 (90)
2021年07月16日 (35)
周排行
更多
分布式事务
2021-07-29
OpenStack云平台命令行登录账户
2021-07-29
getLastRowNum()与getLastCellNum()/getPhysicalNumberOfRows()与getPhysicalNumberOfCells()
2021-07-29
【K8s概念】CSI 卷克隆
2021-07-29
vue3.0使用ant-design-vue进行按需加载原来这么简单
2021-07-29
stack栈
2021-07-29
抽奖动画 - 大转盘抽奖
2021-07-29
PPT写作技巧
2021-07-29
003-核心技术-IO模型-NIO-基于NIO群聊示例
2021-07-29
Bootstrap组件2
2021-07-29
友情链接
兰亭集智
国之画
百度统计
站长统计
阿里云
chrome插件
新版天听网
关于我们
-
联系我们
-
留言反馈
© 2014
mamicode.com
版权所有 联系我们:gaon5@hotmail.com
迷上了代码!