c++ - 2路队列中的访问冲突写入

标签 c++ queue visual-studio-2012

我正在尝试使用 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/

相关文章:

c++ - Eclipse CDT-有没有办法在开始新的启动之前终止以前运行的启动?

c++ - 子类是否需要 Q_INTERFACES 宏?

c++ - 重新加载未定义的行为和序列点

C++ 使用 STL : Stack and Queue

visual-studio - 找不到 TypeScript 编译器

c++ - 如何在不更改 C++ 中的值的情况下更改 json 对象名称?

java - 普通 Java 中类似主题的并发队列

发送包含 JAXB 元素的对象时出现 java.io.NotSerializedException

asp.net - 安装 VS Express 时出现 Web 平台安装程序错误

c# - 更改启动窗口