从C中的链接列表释放内存 [英] Free memory from linked list in C

查看:75
本文介绍了从C中的链接列表释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图释放加载到链表中的文件的分配内存,我设法释放了节点,但是我不知道如何释放文件的值副本的分配内存.

I have been trying to free the allocated memory of a file loaded into a linked list, I have managed to free the nodes, but I can't figure out how to free the allocated memory of the file's values copies.

我已经尝试过类似的事情:

I have tried something like that:

void FreeString(struct node * newNode)
{
    for (int i = 0; i < 5; i++)
    {   
        free(newNode->string);
    }
}

但是编译器会因分段错误而崩溃,并且valgrind仍会指出内存泄漏.

but the compiler would crash with a segmentation fault, and valgrind would still point out to memory leaks.

如果有人能告诉我我在做什么错,并指出正确的方向,将不胜感激.

it would be appreciated if anyone can tell me what am I doing wrong, and point me to the right direction.

完整代码:

Full code:

结构:

typedef struct node
{
    char *string;
    struct node *next;
}node;

//这里的主要功能...

// main function here...

void Push(struct node **RefHead, char *word)
{
    struct node *newNode = NULL;

    newNode = (struct node *)malloc(sizeof(node));

    newNode->string = (char*)malloc(strlen(word) + 1); // can't free this part here
    strcpy(newNode->string, word);
    newNode->next = *RefHead;
    *RefHead = newNode;

}

将文件加载到内存中:

void FileToNode()
{
    struct node *head = NULL, *current = NULL;

    infile = fopen("file.txt", "r");
    if (infile == NULL)
    {
        printf("Could not open file\n");
        exit(1);
    }

    while (fgets(word, sizeof(word), infile))
    {
        Push(&head, word);
    }

    fclose(infile);

    current = head;

    while(current)
    {
        printf("%s", current->string);
        current = current->next;
    }


    freeAll(head);

}

免费功能:

void freeAll(struct node *head)
{
    struct node *current = NULL;

    while ((current = head) != NULL)
    {
        head = head->next;
        free(current);
    }
}

推荐答案

我错过了什么吗?怎么了?

Am I missing something? What's wrong with:

void freeAll(struct node *head)
{
    struct node *current = NULL;

    while ((current = head) != NULL)
    {
        head = head->next;
        free(current->string);
        free(current);
    }
}

这篇关于从C中的链接列表释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆