Search code examples
clistlinked-listnodeserase

Deleting multiple nodes from simple linked list on C


I want to delete all nodes that have the same idteam as key, but it will crash... I know it should also free() the memory, but anyway I thought this should work :S

//defining the struct
struct players {
   int idplayer;
   int idteam;
   struct players *next;
 };

 struct players *first, *last;

//the function to delete the nodes
void delete(int key){
 struct players *post;
 struct players *pre;
 struct players *auxi;

 auxi = first; //initialization of auxi
 while(auxi != NULL) //this should run the loop till the end of the list?
 {
    if(auxi->idteam == key){ //condition to delete
        if(auxi == first) first = auxi->next; //erase for the case the node is the first one
        else pre->next = post; //erase in the case the node is anywhere else
      }
      pre = auxi; //saves the current value of auxi
      auxi = auxi->next; //increments the position of auxi
      post = auxi->next; //saves the position of the next element
     }
}

Solution

  •   auxi = auxi->next; //increments the position of auxi
      post = auxi->next; //saves the position of the next element
    

    When auxi becomes NULL, you will end up doing post = (NULL)->next;, which is an access violation (crash).

    You don't really need post, just do:

    if(auxi->idteam == key){ 
        if(auxi == first) first = auxi->next; 
        else pre->next = auxi->next; // We know auxi is not NULL, so this is safe.
      }