Search code examples
ctreen-ary-tree

C - deleting n-ary tree nodes


I have implemented in C an m,n,k-game with AI. The game works fine but when I have to free the decision tree it always throws an "Access violation reading location" exception.

This is the implementation of the decision tree structure:

typedef struct decision_tree_s {
    unsigned short **board;
    status_t status;
    struct decision_tree_s *brother;
    struct decision_tree_s *children;
} decision_tree_t;


And this is the implementation of the delete_tree function:

void delete_tree(decision_tree_t **tree) {
    decision_tree_t *tmp;

    if (*tree != NULL) {
        delete_tree((*tree)->children);
        delete_tree((*tree)->brother);

        free(*tree);
        *tree = NULL;
    }
}

Solution

  • You are destroying twice the children member: first time in the for loop, the second time after the loop.

    You might want to write your for loop like that:

    for (tmp = tree->brother; tmp != NULL; tmp = tmp->brother) {
        delete_tree(tmp);
    }