带dequeue功能的SegFaulting
SegFaulting with a dequeue function
基本上,我正在使用链表实现一个队列,以尝试模拟人们在一天的过程中在商店排队,他们等待前面的人完成他们的业务。前几个人都很好,但当我第二次调用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
函数有缺陷。看看如果head
是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;
}
另外,是的,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;作为第一行。如我所建议的那样,你将在那之后被安置好。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 带内存和隔离功能的SQLite
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- QML按钮点击功能执行顺序
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 有没有可能有一个只有ADL才能找到的非好友功能
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 文件系统:复制功能的速度秘诀是什么
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 如何在Directwrite中获得给定字体的可用OpenType功能
- 对可变参数使用声明.如何选择正确的功能
- 询问在设计我的手臂模拟器功能表示格式1
- 功能原型的目的
- 带dequeue功能的SegFaulting