Question

Each node in my tree has M children. Some of them may be NULL. After I get done with the tree I am recursively going through each element of the tree and deleting it but that does not free up memory used by the program. First I tried this without defining destructor and then after defining destructor too doesn't help. Please tell me where I am wrong in freeing up memory space. My code for deleting tree is as follows:-

void deleteTree(node* s)
{
    if(s==NULL)
        return ;
    else
    {
        for (int i=0 ; i < M ; i++)
        {
            deleteTree(s->child[i]);
        }
        delete(s);
    }
}

A node contains a string vector ,array of integers and array of pointers to its children.

struct node 
{
    vector<string> stateBoard;
    int Nstate;
    int *NstateAction;
    node** child;
    int depth;
    double Q;
    double *Qvalue;

    node()
    {
        Nstate=0;
        depth = 0;
        NstateAction = new int[M];
        Qvalue = new double[M];
        child = new node *[M];                          //
        for( int i=0 ; i < M ; i++)
        {
            NstateAction[i] = 0;
            child[i]=NULL;
        }
    }
    ~node()
    {
        stateBoard.clear();
        vector<string>(stateBoard).swap(stateBoard);
    }
};
Was it helpful?

Solution

Just delete it. The part that deletes the children of a node should be in the destructor of the node class, not outside. If you don't put it there, deletion isn't recursive, so you will leak grandchild nodes and their subtrees.

OTHER TIPS

If you want to get really technical and practice your C++ 11 I would suggest using smart pointers. Just to be clear I would put all destruction mechanisms to the destructor but smart pointers are a great thing to c++ so as practice you should use them.

So you should declare something like this:

//don't forget to #include<memory>
std::unique_ptr<int> NstateAction;
//don't use vectors as arrays, if the standard library has an alternatve you should use it
std::vector<unique_ptr<int>> child;
std::unique_ptr<double> QValue; 

Smart pointers are pointers that automatically release memory when they go out of scope so this should do the trick.

Now using smart pointers is a bit tricky but here is a question that will help:

c++ - How can i initialize a smart point using a naked new?

Just go to the answers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top