using a linked list in C++ i am attempting to delete a middle node from a series, and then put the series back together.

ex: N1 -> N2 -> N3
N1 -> N3
delete N2

but i am getting a segmentation fault (core dumped) at the point in the code where it tries to put N1->N3 (line 18). the structure is also included. i included multiple if statements in case i was getting the segmentation fault because it was near the end and the program could not delete a non-existant node but they did not help.

any help or explenation is welcome.

code:

void release_memory(const int job)
{
   ALLOCPTR master = alloclist;
   ALLOCPTR tribute = master->next;
   //tribute = tribute->next;
   if(master == NULL)
   {
        cout<<"nothing in the alloc lis"<<endl;
        return;
   }
   while(master != NULL)
   {
        cout<<"id:" << master->id <<endl;
        if(master->id == job)
        {
            cout<<"trying to delete tribute"<<endl;
            //deletes the orriginal master and links the next node back to the list
            if(tribute->next == NULL)
            {
                cout<<"next == null"<<endl;
                delete tribute;
            }
            if(tribute == NULL)
            {
                cout<<"tribute == null"<<endl;
                //delete tribute
            }
            if(tribute->next != NULL)
            {
                cout<<"norm delete and move"<<endl;
                tribute = tribute->next;

                master->next = tribute;
                delete tribute;
            }
            cout<<"deleted tribute"<<endl;
        }
        master = master->next;
        tribute = master->next;
   }
   cout<<"exits release"<<endl;
}

struct:

struct ALLOCNODE // ALLOCTADED LIST NODES
{
  int start_byte;
  int end_byte;
  int size;
  int id;

  ALLOCPTR next;
};

Move lines 3 and 4 down after that first if statement, between lines 10 and 11. If master is null (line 10) then line 4 will cause a seg fault.

In order to delete a node you have to keep track of the most recently visited node.

ALLOCPTR* current = master;
ALLOCPTR* prev = NULL;
while( current )
{
   if( current->id == job)
   {
      if( prev == NULL )
      {
         // delete head of the list
         prev = master;
         master = master->next;
         delete prev;
      }
      else
      {
          prev->next = current->next;
          delete prev;
      }
      break; // exit while loop
   }
   prev = current;
   current = current->next;
}

Edited 2 Years Ago by Ancient Dragon

i am still getting a segmentation fault(core dumped), and im thinking it is because i am trying to access a null node

Can you post the complete program? Are you setting the next pointer to NULL after a new node is allocated? If you don't do that then the rest of the program might attempt to dereference an invalid pointer.

This article has been dead for over six months. Start a new discussion instead.