关于Debug Assertion Failed问题
2024-08-29 19:00:09
书上代码:
#include<stdio.h>
#include<stdlib.h> /* 提供malloc()、free()函数 */
#include<string.h> #define TSIZE 45 struct film {
char title [TSIZE];
int rating;
struct film *next; /* 指向链表的下一个结构 */
}; int main()
{
struct film *head=NULL; /* 链表头 */
struct film *prev,*current; /* 定义两个film结构型指针 */
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; /* 将地址赋给结构指针指向前一个结构中的next成员 */
current->next=NULL; /* 用空指针给current指向的第二个结构成员next赋空值 */
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=current->next;
} printf("Bye!\n");
return 0;
}
迷惑:
去掉 current=head; 后程序才能正常运作。
网上查了一下,也有人提过这个问题,但他的解决方法是将free直接去掉,运行就没问题了。
然后我就奇怪了,难道不用释放内存吗?
解决:
//再来说说这个问题,释放的代码确实是错误的,正确的释放操作为: /* 再定义一个结构体类型的指针 temp */
while(current)
{
temp = current;
current = current -> next;
free(temp);
}
最新文章
- keyset获取元素
- [IT新应用]如何部署CITRIX 虚拟桌面
- Webpack教程一
- 20150414---ListView简介(web)
- UVa 11105 (筛法) Semi-prime H-numbers
- [Everyday Mathematics]20150103
- Find The Multiple(poj 1426)
- NetworkX学习笔记-5-NetworkX中怎样对多个网络赋属性,并根据属性排序
- SignalR实现实时日志监控
- [转]Windows7 64bit下配置Apache+PHP+MySQL
- Docker 部署DropWizard
- centos6 网卡配置,多IP设置
- 安卓服务Service详解
- DJANGO_SETTINGS_MODULE is undefined报错的解决
- phpstorm在项目中查找某个字符串
- ubuntu 印象笔记
- spring-事件通知实现
- c/c++ sizeof运算符详解以及对象大小
- Memcached与redis的比较--stackoverflow(转)
- 20145334赵文豪《网络对抗》shellcode注入&;Return-to-libc攻击深入
热门文章
- 在spring Boot中使用swagger-bootstrap-ui(原文)
- supervisor的使用点滴
- Git - 05. git log &; git show
- BufferedInputStream 介绍
- mongodb的一些操作
- angular2 单元测试 路由相关
- python 在linux上面安装beautifulsoup4(bs4) No module named &#39;bs4&#39;
- SPAN, RSPAN, ERSPAN
- Kettle-User Defined Java Class使用-大写转换
- Java面向对象编程 -6.4