gpt4 book ai didi

c++ - 具有出队功能的段错误

转载 作者:太空狗 更新时间:2023-10-29 23:06:28 24 4
gpt4 key购买 nike

基本上,我正在使用链表实现一个队列,以尝试模拟人们在一天中在一家商店排队,他们一直等到前面的人完成他们的业务。前几个人过得很好,但是当我接到第二次 dequeue 电话时,它出现了段错误。 gdb 调试器说错误来自这一行 head=current->next; (其中 current=head)。

这是我的出列函数:

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

这是入队函数(以防入队时导致内存泄漏):

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

如果你们能就段错误可能发生的位置提供任何帮助,那将是非常棒的,在此先感谢。

P.S.如有必要,我可以提供更多信息。

最佳答案

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

关于c++ - 具有出队功能的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15628089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com