“Access violation reading location” error on C++

496 views Asked by At

I'm a beginner in C++. I have written this code that generates a modified version of Quadtrees. When I run it, I get the "access violation reading location” error. I have two classes:

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

and:

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

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

tree_builder function:

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

delete_helper function, that's where I get the error:

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;
    }
}

main:

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

P.S. Sorry my code is long, I tried to make it as short as I can!

1

There are 1 answers

10
Millie Smith On

You're deleting p->id four times.

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

Another potential problem is deleting uninitialized children because the child array isn't initialized to 0s. Are you sure every node has four valid children?