Search code examples
clinked-listdynamic-memory-allocationfreesingly-linked-list

Why don't we use free(node) when inserting in a linked list?


void push(struct node **head, int data)
{
        struct node* newnode = malloc(sizeof(struct node));
        newnode->data = data;
        newnode->next = *head;
        *head=newnode;

}

I came across this function, I wonder why didn't we use free(newnode) since we affected its value to *head and we no longer have use of it?


Solution

  • If you will free the node pointed to by the pointer newnode then as a result the pointer *head due to this statement

    *head=newnode;
    

    will point to a deleted node. As a result the pointer *head will be invalid.

    That is after this statement

    *head=newnode;
    

    the both pointers *head and newnode point to the same one node. If you will write

    free( newnode );
    

    or

    free( *head );
    

    the pointed node will be deleted. So you nothing added to the list. What you was going to add to the list you deleted.:) And moreover you substituted a correct value in the pointer *head (before calling the function) for an invalid value (address) that points nowhere after deleting the node.

    Pay attention to that it would be more correct to define the function the following way

    int push( struct node **head, int data )
    {
        struct node *newnode = malloc( sizeof( struct node ) );
        int success = newnode != NULL;
    
        if ( success )
        {
            newnode->data = data;
            newnode->next = *head;
    
            *head = newnode;
        }
    
        return success;
    }
    

    In that case the function will not have undefined behavior when there is no enough memory to allocate a new node. And the user of the function can check whether adding a new node was successful.