【发布时间】:2012-11-03 20:33:41
【问题描述】:
我正在尝试使用 c++ 创建一个两侧队列。 我正在使用 Visual Studio 2012 并不断获得:
First-chance exception at 0x00D95A29 in Console_Assignment1.exe: 0xC0000005: Access violation writing location 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;
}
}
}
提前感谢您的帮助!
【问题讨论】:
-
为什么?你发现
std::deque有问题吗? -
你试过在调试器中运行吗?它将帮助您找到崩溃的位置,并让您检查变量以帮助您了解可能导致崩溃的原因。但是,您是否想过当您将 first 节点排入队列时会发生什么,这意味着没有 current 第一个节点(即
this->getFirst()返回NULL)?出队函数也有类似的问题。 -
我认为您将不得不发布所有代码。你很可能有多个问题。问题也很可能与您认为的不同。建议总是一样的,发布 smallest、complete、compilable 程序,你可以管理它仍然有你试图解决的错误。换句话说,做一些工作来删除不相关的东西,但要发布所有内容。
标签: c++ queue visual-studio-2012