Home > Net >  Why is it necessary to "free" a node?
Why is it necessary to "free" a node?

Time:10-04

You are given a pointer/ reference to the node which is to be deleted from the linked list of N nodes.

Input:
N = 2,
value[] = {1,2},
node = 1 ,
Output: 2

I am writing code like this -

void deleteNode(Node *del)
{
    del->data=(del->next)->data;
    del->next=(del->next)->next;
}

But the given answer is -

void deleteNode(Node *del) {    
    Node* temp = del->next;
    del->data = temp->data;
    del->next = temp->next;
    free(temp);
}

Both the answers are correct , but i don't know whether my method is wrong or right?

CodePudding user response:

Your code has a memory leak. That means that the memory allocated for the node (presumably by malloc) is not freed in deleteNode, but the references to it are. The consequence is that your program could run out of memory eventually and crash.

CodePudding user response:

You are given a pointer/ reference to the node which is to be deleted from the linked list of N nodes.

The description does not match the given answer. For the given answer, the parameter is a pointer to the node just before the node to be deleted. This would be more clear if the function were written as:

void deleteNode(Node *prior) {    
    Node* current = prior->next;    /* current = pointer of node to be deleted */
    if(current == NULL)             /* exit if there is no current node */
        return;
    prior->next = current->next;    /* remove node from list */
    free(current);                  /* only if node was allocated with malloc */
}

/* this line is a mistake, so I removed it */
    prior->data = current-> data

The problem with this is the first node can't be deleted, unless there is a head | dummy node that points to the first node of a list. An alternative is to use a pointer to pointer to node:

/* from the calling code */
    Node **ppdel;
    /* ... */
    ppdel = &head;                  /* if removing 1st node on list */
/* ... or  ... */
    ppdel = &(prior->next)          /* for all but 1st node on list */
    deleteNode(Node **ppdel);
/* ... */
void deleteNode(Node **ppdel) {    
    Node* current = *ppdel;         /* current = pointer of node to be deleted */
    if(current == NULL)             /* exit if there is no current node */
        return;
    *ppdel = current->next;         /* remove node from list */
    free(current);                  /* only if node was allocated with malloc */
}
  • Related