C ++上的“访问冲突读取位置”错误

时间:2017-09-07 15:42:13

标签: c++ destructor quadtree

我是C ++的初学者。我编写了这段代码,生成了Quadtrees的修改版本。当我运行它时,我得到"访问冲突读取位置“错误。我有两个班:

class TreeNode
{
public:
    TreeNode *parent;
    TreeNode *child[4];
    int *id;
    ...
TreeNode(..., int *_id, ...): ..., id(_id),... {}
    };

class QuadTree
{
private:
    ...
    TreeNode *root;
    void tree_builder(TreeNode *&p,...);

public:
    QuadTree(...);
    ~QuadTree() {delete_helper(root);}
};

tree_builder函数:

void QuadTree::tree_builder(TreeNode *&p, ...)
{
    p = new TreeNode();
    p->id = new int[2 * length]; 
    ...
}

delete_helper函数,我收到错误的地方:

void QuadTree::delete_helper(TreeNode *& p)
{
    if (p != NULL)
    {
        for (int i = 0; i < 4; i++)
        {
            delete_helper(p->child[i]);
        }
        delete[] p->id;
        delete p;
        p = NULL;
    }
}

主:

int main()
{
    QuadTree *tree;
    tree = new QuadTree(length, xyseed);
    ...
        delete tree;
    ...
        return 0;
}

P.S。对不起,我的代码很长,我尽量做到尽可能短!

1 个答案:

答案 0 :(得分:1)

您要删除p-&gt; ID四次。

for (int i = 0; i < 4; i++)
{
    ....
    delete[] p->id;
}

另一个潜在的问题是删除未初始化的子节点,因为子数组未初始化为0。你确定每个节点都有四个有效的孩子吗?