Home:ALL Converter>C Linked List memory leak

C Linked List memory leak

Ask Time:2016-02-16T06:55:05         Author:user3784695

Json Formatter

I can't figure out why my linked list has a memory leak.

I have a method called insertAtFront()

void insertAtFront(Node **head, char *key) {
    Node *new =  malloc(sizeof(Node));
    if (!new)  fatal("Malloc of new Node failed");
    new->word = key;
    new->next = *head;
    *head = new;
}

Then I have a removeAtFront() method that frees the node.

void removeAtFront(Node **head) { 
    Node *newhead = (*head)->next;
    free(*head);
    *head = newhead;
}

If I only add one node and then remove it, there is no leak. If I remove more than one node, valgrind shows a leak proportional to how many additional nodes were added. I really can't understand why this happens as the node is freed. Any ideas?

Author:user3784695,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/35420629/c-linked-list-memory-leak
yy