Andrew Polidori
Andrew Polidori

Reputation: 63

Deleting an entire linked list in C, gone wrong

So I'm trying to use this function to delete entire singly-linked lists in C.

    void zeroList( struct node *head)
    {
        struct node* tempDelete;
        struct node* current = head;

        while(current != NULL)
        {
            tempDelete = current;
            current = current->next;
            free(tempDelete);

        }   
    }

I am having a problem though, because when I attempt to verify that the list itself has been deleted(by printing it). I'm left with something that looks like this:

{ 0->146513968->146513952->146513936-> NULL }
{ 146513920->146514048->146514032->146514016->146514000-> NULL }
{146513984->146514064->146514080->146514096->146514112->146514128->146514144->146514160->146514176-> NULL }

I was under the impression that the nodes wouldn't still be there, or at the very least that they'd contain NULL values. Can anyone explain why I'm getting these strange garbage numbers?

Upvotes: 2

Views: 158

Answers (1)

Charles Welton
Charles Welton

Reputation: 861

Once you free memory, it's contents are undefined, and you should not touch them. This is the same reason why you shouldn't set a pointer to a random value you chose(the OS needs to give you access to it.)

The values you're seeing is garbage, and expected, as the OS does not zero memory. If you want to make sure to not have anything on memory, you need to clear the pointers yourself:

current = current->next;
tempDelete->next = NULL;

PS.: This however, doesn't guarantee the head will be NULL by the end of the function.

Upvotes: 2

Related Questions