c - 如何释放我的单链表程序?

标签 c if-statement malloc singly-linked-list

我有 2 个关于我的代码的问题:

  1. 为什么 struct node *a,*b; 不能在 create() 中工作?我收到此消息:b 已使用但未初始化。它在 if 语句中也不起作用。
  2. 如果我们在普通程序中使用 malloc(),我们可以像这样使用 free -> free(variablename);,但是我如何去释放一个单链接名单?

这是我的代码:

#include<stdio.h>
#include<conio.h>
#include<malloc.h>

struct node
{
int d;
struct node *next;
}*start=NULL;struct node *a,*b;

void create()
{
    a=(struct node *)malloc(sizeof(struct node));
    printf("Enter the data : ");
    scanf("%d",&a->d);
    a->next=NULL;

    if(start==NULL)
    {
        start=a;
        b=a;
    }

    else
    {
        b->next=a;
        b=a;
    }
}

void display()
{

    struct node *a;
    printf("\nThe Linked List : ");
    a=start;

    while(a!=NULL)
    {
        printf("%d--->",a->d);
        a=a->next;
    }
    printf("NULL\n");
}


void main()
{
    char ch;
    do
    {
        create();   
        printf("Do you want to create another : ");
        ch=getche();
    }

    while(ch!='n');

    display();
    free(a); // i don't know is this crt?
}

最佳答案

您必须单独释放列表中的每个元素。由 malloc 分配的每个内存片必须用 free 释放。

不要在程序结束时调用 free(a),而是调用 freenodes()

void freenodes()
{
    struct node *a;
    a = start;

    while(a != NULL)
    {
      struct node *freenode = a ;
      a = a->next;
      free(freenode) ;
    }
}

关于c - 如何释放我的单链表程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22479645/

相关文章:

c++ - C++Builder 6 中的最大内存分配

c - C语言中字符串的循环

java - boolean 值没有按预期改变

powershell - 我的 if 语句有问题吗?

c++ - 带有初始化器的堆上的多维数组

c - C中的多维字符串数组

c - 奇怪的行为c自愿溢出

c - 在线程中设置全局变量

c - 在 x86 汇编中交换 2 个整数

jQuery if hasClass 操作