Home:ALL Converter>Memory Leak in c linked list insert function

Memory Leak in c linked list insert function

Ask Time:2020-09-17T04:31:46         Author:Nice

Json Formatter

I'm trying to implement a linked list and according to LeakSanitizer I have a leak in my program in this function. The function inserts new nodes and keeps them sorted in ascending order.

enter image description here


typedef struct Node {
    int data;
    struct Node *next;
} node;

void insert(node **head, int num) {
    node *temp_node = NULL, *curr = NULL;

    temp_node = (node *)malloc(sizeof(node));

    temp_node->data = num;
    temp_node->next = NULL;

    if (*head == NULL) {
        *head = temp_node;
    } else
    if ((*head)->data >= temp_node->data) {
        temp_node->next = *head;
        *head = temp_node;
    } else {
        curr = *head;
        while (curr->next != NULL && curr->next->data < temp_node->data)
            curr = curr->next;

        temp_node->next = curr->next;
        curr->next = temp_node;
    }
}

This is the call to insert in my main function

node *head;

...other code...

insert(&head, number);

...other code....

free(head);

Any advice is really appreciated.

Author:Nice,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/63927550/memory-leak-in-c-linked-list-insert-function
yy