Austin
Austin

Reputation: 7339

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.

Upvotes: 1

Views: 254

Answers (2)

Abhijit Annaldas
Abhijit Annaldas

Reputation: 667

To just add to what @dasblinkenlight said, you need not delete/remove it explicitly. Since *temp is inside the function's scope, it will be gone once the function returns.

Since you are concerned about the unused memory, just a reminder - pointer takes 4 bytes on a 32bit machine and 8 bytes on a 64 bit machine and, not the sizeof(DLL_Node) as you might be thinking.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

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.

Upvotes: 5

Related Questions