简体   繁体   中英

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?

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.

You mustn't do free(newnode); here because the new node is added to the list and therefore will be used later.

Also the variable newnode itself is (typically) allocated on the stack and will be freed automatically when exiting from the function, so you don't need to manyally free that.

Because *head will refer the dead newnode . You have to free them in the end of the code. Actually, you don't need to get head as double pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM