Free memory from linked list in C

北战南征 提交于 2019-12-14 04:22:47

问题


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

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:

The struct:

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;

}

Loading the file into memory:

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

}

The Free function:

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

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

回答1:


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



回答2:


It's not the problem, but you should probably replace:

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

with:

newNode->string = strdup (word);

The problem is this:

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

Once you call free, newNode->string no longer points to an allocated object (because you just freed it). So you can't pass it to free again.



来源:https://stackoverflow.com/questions/33113510/free-memory-from-linked-list-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!