简体   繁体   English

链表-Free()节点导致程序崩溃

[英]Linked List - Free() nodes causes program to crash

I am new to linked lists in c and wrote a little program in c, creating nodes and when I try to free the allocated memory my program crashes. 我不熟悉c中的链接列表,并在c中编写了一个小程序,创建了节点,当我尝试释放分配的内存时,我的程序崩溃了。 I don't know what is causing this error, so I hope you can help me. 我不知道是什么原因导致此错误,所以希望您能为我提供帮助。 My code: 我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct list
{
    int data;
    struct list *link;
} node;
node *createnode();
int main()
{
    node *a = createnode(); //create first node
    node *start = a;
    printf("Value of first node: ");
    scanf("%d", &a->data);
    for(int j = 0; j<3; j++) //create three nodes
    {
        a->link = createnode();
        a = a -> link;
        printf("Value of node %d: ", j+1);
        scanf("%d", &a->data);
        if(j==2)
        {
            a -> link = NULL;
        }
    }
    a = start;
    while(a != NULL)
    {
        printf("%d -> ", a->data);
        a = a -> link;
        if(a==NULL)
        {
            printf("null");
        }
    }
    a = start;
    while(a != NULL)
    {
        a = start;
        start = a -> link;
        free(a);
    }



    return 0;
}
node *createnode()
{
    return malloc(sizeof(node));
}
while(a != NULL)
{
    a = start;
    start = a -> link;
    free(a);
}

must be 一定是

while(start != NULL)
{
    a = start;
    start = a -> link;
    free(a);
}

and of course a = start; 当然a = start; just before is useless 就在之前是没有用的

{edit} {编辑}

additional remark, to do if(j==2) { a -> link = NULL; } 附加说明, if(j==2) { a -> link = NULL; } if(j==2) { a -> link = NULL; } is a bad choice, because just after you test again the value of j and if you have to change the number of loops you have to do 2 changes. if(j==2) { a -> link = NULL; }是一个不好的选择,因为在再次测试j的值之后,如果必须更改循环数,则必须进行2次更改。 Better to remove it and to add a -> link = NULL; 最好将其删除并添加a -> link = NULL; directly after the loop (no test needed) 循环后立即进行(无需测试)

Replace this: 替换为:

    a = start;
    while(a != NULL)
    {
        a = start;
        start = a -> link;
        free(a);
    }

with: 有:

    while(start != NULL)
    {
        a = start;
        start = a -> link;
        free(a);
    }

In the original loop, a was being set to the new value without being tested. 在原始循环中,将a设置为新值而不进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM