0

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?

Xirol
  • 303
  • 4
  • 10
  • 3
    Please post a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Also not that they say [you shouldn't cast the result of `malloc()` in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – MikeCAT Mar 16 '16 at 00:51
  • 4
    This is definitely not correct because you defined `free()` and calling it inside the function will fail into infinite recursion. – MikeCAT Mar 16 '16 at 00:52
  • 1
    Note: the local variable `start` won't be affected by `runmenu(......,start);` unless the pointer to `start` is passed in `......` or you invoke *undefined behavior*. – MikeCAT Mar 16 '16 at 01:23
  • I saw that, and ended up calling free_list in my runmenu – Xirol Mar 16 '16 at 01:54

1 Answers1

1

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278