-3

由于某种原因,我的程序在完成复制构造函数测试后在析构函数中设置调试后中断。我通过它进行了调试,发现由于某种原因,头指针在进入析构函数后立即恢复为垃圾,即使头指针在退出复制构造函数时正确指向第一个节点,从而导致分配我的析构函数中的第一个链接字段失败。

当我运行考试存根时,它通过了堆测试,并且在析构函数中断之前通过了复制构造函数测试,为什么会这样?顺便说一句,我没有包含我的所有代码,因为我不想简单粘贴固定代码,我只想知道为什么会发生这种情况,以便我可以学习..我真的不想恢复发布这个问题,但我'一直在试图弄清楚为什么这东西会这样,它让我发疯..

这是我的析构函数,带有中断点

PriorityQueue::~PriorityQueue( )
{
        Node *nodeptr, *nextnode=NULL;
        nodeptr = head_ptr;                     // CONTAINS GARBAGE AT POINT OF BREAK
        while ( nodeptr != NULL)
        {
                nextnode = nodeptr->link;  // THIS IS WHERE IT BREAKS,
                delete nodeptr;             //BECAUSE ITS ASSIGNING GARBAGE FROM HEAD POINTER
                nodeptr = nextnode;
        }
        many_nodes = 0;
        head_ptr = NULL;
}

这是我的复制构造函数

PriorityQueue::PriorityQueue(const PriorityQueue& source)
{   
    many_nodes = source.many_nodes;         // copy node count

    Node * node1 = NULL;                    // declare node pointer
    Node * precursor = NULL;                // declare precursor for new list 
    Node * copycursor = NULL;               // declare cursor for copy list

    copycursor = source.head_ptr;           // set copy cursor to source head

    int x = 0;
    while(x < many_nodes)               // start a loop for num of nodes
    {
        node1 = new Node;               // point node1 to a new allocated node

        node1->data = copycursor->data;         // copy over data to that node
        node1->priority = copycursor->priority;

        if (copycursor == source.head_ptr)      // if we're at the head
            head_ptr = node1;               // set new head to copy head

        if(precursor != NULL)               // if this isn't the first iteration
            precursor->link = node1;            // link the last node to this new node

        precursor = node1;              // precursor is now on this node
        copycursor = copycursor->link;          // copy cursor is now advanced

        x++;
    }
}

我还添加了一张我的观点的图片,它在析构函数中中断以更容易地显示值 我的休息点

通过复制构造函数和堆测试..

4

3 回答 3

2

该错误在您的复制构造函数中。如果many_nodes为零,则head_ptr未初始化。这在屏幕截图中得到证实:在崩溃时,many_nodes为零。(这意味着您声称“头指针正确指向第一个节点,因为它退出复制构造函数”是不正确的。头指针没有恢复为垃圾。它已经是垃圾。这可能是阻止人们诊断的原因真正的问题。)

更新:现在你编辑了你的问题,所以它现在是一个完全不相关的问题,所以这个答案和约翰的答案没有意义。这个问题现在对网站的未来访问者毫无用处,他们会阅读问题和答案并说“这完全是胡说八道”。

于 2013-10-13T13:37:34.707 回答
0

事实证明,在析构函数中添加对 0 many_nodes 的测试可以防止复制构造函数和赋值运算符崩溃,并且复制构造函数和赋值运算符仍然按预期工作。此处的屏幕截图证实了这一点。感谢 Ray 指出了 0 案例。现在每个阅读这个线程的人都知道,如何为链表类编写一个完整的析构函数和复制构造函数。

if(many_nodes == 0)
{
    head_ptr = NULL;
    return;
}

在此处输入图像描述

于 2013-10-14T05:45:40.283 回答
0

你需要改变这个

    node1->data = copycursor->data;         // copy over data to that node
    node1->priority = copycursor->priority;

对此

    node1->data = copycursor->data;         // copy over data to that node
    node1->priority = copycursor->priority;
    node1->link = NULL;

您遇到的问题是列表中的最后一个节点没有将其链接字段设置为 NULL(我假设 Node 构造函数没有这样做)。

于 2013-10-13T08:05:45.027 回答