C中链表的可用内存

时间:2015-10-13 22:11:52

标签: c struct memory-leaks free

我一直试图释放加载到链表中的文件的已分配内存,我已经设法释放节点,但我无法弄清楚如何释放文件的分配内存' s值复制。

我尝试过类似的东西:

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

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

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

  

完整代码:

结构:

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

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

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

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

这不是问题,但你应该更换:

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