qq_45947498 2022-03-06 22:50 采纳率: 100%
浏览 109
已结题

c语言链表,要不要释放内存(free)

我不知道是我代码写错了还是怎么
麻烦各位大家看看

//单链表前插法 
#include<stdio.h>
#include<stdlib.h>
struct Student
{
    int num;
    
    struct Student *next;    
}; 
struct Student *create()
{
    struct Student *head,*n;//n是新节点 
    int i;
    head=(struct Student *)malloc(sizeof(struct Student));
    head->next=NULL;//头指针指向为空
    while(n->num!=0)
    {    
        n =(struct Student *)malloc(sizeof(struct Student));
        printf("num=");
        scanf("%d",&n->num);
        n->next=head->next;//新节点指向head节点指向的节点
        head->next=n; 
    }    
//    free(n);//添加free输出不正确 
    return head;
} 
void print(struct Student *head)
{
    int s;
    struct Student *temp;
    printf("-----------the list -----------");
    temp=head;
    while(temp!=NULL)
    {
        printf("the num=%d\n",temp->num);
        temp=temp->next;
        
    }
}
int main(){
    struct Student *head;//定义一个头指针 
    head=create();
    print(head);
    return 0;
}

不加free

img


加上free

img

  • 写回答

3条回答 默认 最新

  • yun6853992 2022-03-06 23:17
    关注

    链表用的就是这个指针,你不应该在插入的时候free的才是对的,但是你应该free是在链表删除一个节点或者删除的时候依次free掉这里的内存。

    你得代码能过? 第一次用while的时候 你的n没有初始化啊,这指针指向。。。

    你先把这个没初始化改了,然后看有问题吧,可能是这里导致的,没初始化的话,内存是乱的。
    至于创建的逻辑 看起来没问题,至少我没看出问题

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 3月15日
  • 已采纳回答 3月7日
  • 创建了问题 3月6日

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格