Xirol
Xirol

Reputation: 303

Freeing Nodes in Linked List

I'm trying to free each node in my linked list which was allocated in the addRec function.

CHANGE: Renamed my free funcion to free_list.

My call to free is as follows:

main()
{
    struct record * start = NULL;
    runmenu(......,start); //Ends when user chooses option to quit
    .
    . 
    free_list(start);
}

void runmenu(.....,struct record * pstart)
{
    addRec(&start,....);
}

void addRec(struct record ** start,.....)
{
    struct record *toAdd;       
    toAdd = (struct record*)malloc(sizeof(struct record));

    if (*start = NULL)
    {
        *start = toAdd;
    } else {
        struct record *current = start;
        toAdd->next = current->next;
        current->next = toAdd;
        . 
        . //Adds into linked list
    }
}

My free function looks like:

void free_list(struct record* head)
{
    struct record *temp;

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

I still seem to be having memory leaks. Was this correct?

Upvotes: 0

Views: 41

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753585

You've provided your own function called free(), which means that the standard one isn't available. Rename your function free_list() and call that in main() to release the list. Inside the (now renamed) free_list() function, you still call the standard free() function.

Upvotes: 1

Related Questions