带dequeue功能的SegFaulting

SegFaulting with a dequeue function

本文关键字:SegFaulting 功能 dequeue      更新时间:2023-10-16

基本上,我正在使用链表实现一个队列,以尝试模拟人们在一天的过程中在商店排队,他们等待前面的人完成他们的业务。前几个人都很好,但当我第二次调用dequeue时,它把我隔离了。gdb调试器说错误来自这一行head=current->next;(当前=头)。

下面是我的dequeue函数:
    void BankQueue::dequeue()
   {
      Node* current=head;
      head=current->next;
      if(head!=NULL)
      {
            head->prev=NULL;
      }
      delete current;
   }

下面是enqueue函数(如果在排队时我导致内存泄漏):

    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;
         }

任何帮助你的家伙可以提供的部分故障可能发生的地方将是惊人的,提前感谢。

注:如有需要,我可以提供更多信息。

您的dequeue函数有缺陷。看看如果headNULL会发生什么:

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;
}

另外,是的,tail也需要在那里更新。

// 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,回应你的评论:

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;
    }
}

我有一个评论,但我将展开,因为我认为这是最有可能的问题。

你的dequeue函数不会重置tail指针。因为enqueue函数使用它来确定队列是否为空,所以如果清空队列然后再次放入项目(因为head将为NULL),则会出现问题。

in dequeue put a condition if(!head) return;作为第一行。如我所建议的那样,你将在那之后被安置好。