Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SegFaulting with a dequeue function

Basically, I'm implementing a queue using a linked list to try and simulate people standing in line at a store over the course of the day and they wait until the person in front of them finishes their business. The first few people go through fine but when i get to the second call of dequeue it segfaults me. The gdb debugger says the error comes from this line head=current->next; (where current=head).

Here is my dequeue function:

    void BankQueue::dequeue()
   {
      Node* current=head;
      head=current->next;
      if(head!=NULL)
      {
            head->prev=NULL;
      }
      delete current;
   }

Here is the enqueue function(in case when enqueueing i'm causing a memory leak):

    void BankQueue::enqueue(Customer s)
    {
         Node* node= new node;
         node->data=s;
         node->next=NULL;
         if(tail==NULL)
         {
              head=node;
              tail=node;
              node->prev=NULL;
         }
         else
         {
              node->prev=tail;
              tail->next=node;;
              tail=node;
         }

Any help you guys can offer as to where the segfault could be occuring would be amazing, thanks in advance.

P.S.I can provide more information if necessary.

like image 321
Thomas Avatar asked Dec 06 '25 08:12

Thomas


1 Answers

Your dequeue function is flawed. Look what happens if head were to be NULL:

void BankQueue::dequeue()
{
    // current == NULL
    Node* current = head;
    // Setting head to NULL->next
    // This will reference memory location 0x00000000 + (some offset)
    head=current->next;
    // This is undefined, but it most likely will return true
    if(head!=NULL)
    {
        // undefined
        head->prev=NULL;
    }
    // Delete NULL
    delete current;
}

Also, yes, tail needs to be updated in there too.

// After you've made sure that head is valid
if (head == tail) {
    // there is only node, so we just clear tail
    tail = NULL;
}
// Then you proceed with removal

Thomas, in response to your comment:

void BankQueue::dequeue()
{
    // If the queue has instances
    if (head)
    {
        // If there is only one instance
        if (head == tail)
        {
            tail = NULL;
        }

        // set the new head
        head = head->next;
        // delete the old head if it exists
        if (head->prev)
        {
            delete head->prev;
        }
        // null data
        head->prev = NULL;
    }
}
like image 126
user123 Avatar answered Dec 08 '25 22:12

user123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!