zoukankan      html  css  js  c++  java
  • 关于Debug Assertion Failed问题

      书上代码:

    #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]!='')                /* 接收键盘上输入的字符串 */
        {
            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",&current->rating);
            while(getchar()!='
    ')/* 接收回车符 */
                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:
    ");
        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;
    }
    

      迷惑:

    去掉 current=head; 后程序才能正常运作。
    网上查了一下,也有人提过这个问题,但他的解决方法是将free直接去掉,运行就没问题了。
    然后我就奇怪了,难道不用释放内存吗?
    

      解决:

    //再来说说这个问题,释放的代码确实是错误的,正确的释放操作为:
    
    /* 再定义一个结构体类型的指针 temp */
    while(current)
    {
        temp = current;
        current = current -> next;
        free(temp);
    }
    

      

  • 相关阅读:
    Linux学习之路3-HelloWorld
    Linux学习之路2-linux系统烧写
    Linux学习之路1
    linux常用命令总结
    禅道配置发邮件功能
    SHELVE模块
    PICKLE模块
    JSON_dump和load
    json.dumps和loads方法
    模块调用
  • 原文地址:https://www.cnblogs.com/darkchii/p/6964438.html
Copyright © 2011-2022 走看看