Search code examples
cpointersfreedoubly-linked-list

Should I free a temp pointer used to traverse a linked list?


If I have something like:

function(DLL *dll) {
    DLL_Node *temp = dll->head

    // do stuff with temp like traverse list with temp=temp->next

    // say when done, temp = dll->tail, should I free(temp) or leave it alone?
}

I'm still not very experienced with pointers, it seems like I created an extra pointer, but it just points to a position in the list, so I shouldn't free it and it will get cleared when function ends?

By the way I defined DLL and DLL_Node like this:

typedef struct dll_node {
    int data;
    struct dll_node *prev;
    struct dll_node *next;
} DLL_Node;

typedef struct DLL_ {
    int count;
    DLL_Node *head;
    DLL_Node *tail;
} DLL;

I saw a recommendation for the program valgrind for testing for memory leaks and it says definitely lost and indirectly lost are both 0 bytes, but possibly lost is 2,064 bytes. Not sure what that means exactly or if it's relevant.


Solution

  • Calling free does not free a pointer, it frees whatever the pointer points to. Simply declaring and using a pointer does not call for freeing, so you do not need to free a pointer that has been used to traverse a list.

    General rule is that you need to call free on everything that has been returned to you by malloc/calloc/realloc. There needs to be only one call of free on each allocated block. Freeing the same block twice results in undefined behavior.