从C中的链表中释放内存

Free memory from linked list in C

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

我试过类似的东西:

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

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

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

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);
    }
}

我错过了什么吗?有什么问题:

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

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

这不是问题,但您可能应该更换:

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

与:

newNode->string = strdup (word);

问题是这样的:

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

调用 free 后,newNode->string 不再指向分配的对象(因为您刚刚释放了它)。所以你不能再把它传递给free