我正在尝试使用 C++ 创建一个双向队列。 我正在使用 Visual Studio 2012 并不断获得:
Console_Assignment1.exe 中 0x00D95A29 处的第一次机会异常:0xC0000005:访问冲突写入位置 0x00000008。
我想我遇到了指针问题(可能是在尝试取消引用我不应该引用的内容)。 到目前为止,我发现问题的运气为零,非常感谢再看一眼。
(代码太长无法粘贴,所以我只复制我认为给我带来问题的功能。) 也许只是一个小小的概述。我有一个节点类,它包含两个指向节点的指针(下一个和上一个)和一个 int(值)。和一个队列类,它包含两个指向节点的指针(第一个和最后一个)和一个 int(大小)。
// enqueueBeg - adds a new node at the beginning of the queue.
void DBL_Queue::enqueueBeg(int insert_val)
{
node* new_node = new node(insert_val); // Creates the new node.
new_node->setNext( this->getFirst() ); // Connects the new node to the first in the queue
this->getFirst()->setPrev( new_node ); // Connects the first node in the queue to the new one
this->setFirst( new_node ); // Sets the new node as the first in the queue
this->setSize ( this->get_queue_size() + 1 ); // adds 1 to the size of the list
// dequeueBeg - removes the first node of the queue.
int DBL_Queue::dequeueBeg()
{
int ret_value = this->getFirst()->getVal();
node* old_node = this->getFirst();
this->setFirst( this->getFirst()->getNext() ); // Sets the second node in the queue as the first.
this->getFirst()->setPrev( NULL ); // Removes the link between the new first new and the old one.
this->setSize( this->get_queue_size() - 1); // Removes 1 from queue size
delete old_node; // Deletes the node that use to be first.
return ret_value; // Returns the value of the old node.
// DBL_Queue Destructor
DBL_Queue::~DBL_Queue()
{
if (this->first == NULL) // if queue is empty do nothing
return;
else
{
while (this->first->getNext() != NULL) // go through all nodes and delete them one by one
{
node* deletion = this->getFirst();
this->setFirst( this->getFirst()->getNext() );
delete deletion;
}
}
}
在此先感谢您的帮助!
最佳答案
我认为这是你的问题:
while (this->first->getNext() != NULL) // go through all nodes and delete them one by one
{
node* deletion = this->getFirst();
this->setFirst( this->getFirst()->getNext() );
delete deletion;
}
当你删除最后一个节点时,你会调用
this->setFirst( null );
因为 this->getFirst()->getNext()
将为空,对吗?
那么 while(this->first->getNext()
变成 null->getNext()
为什么不只是
while(this->first != NULL)
?
编辑:除非你真的关心最小化析构函数的运行时间,否则为什么不
while(this->getFirst() != NULL) {this->dequeueBeg;}
关于c++ - 2路队列中的访问冲突写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13213242/