0

我在使用 destroy_tree 函数删除 C++ 中的树时遇到问题。编译器说*** glibc detected *** <path>: free(): invalid pointer: 0x00007f37590d3778 ***。这是我的destroy_tree功能:

void Tree::destroy_tree(node** parent) {

if ( (*parent) != NULL ) {

    for (int i=0; i<NUM_ELEMS; i++) {
        destroy_tree( &((*parent)->leaves[i]) );
    }

    if ( (*parent)->zone_id != NULL ) {
        delete (*parent)->zone_id;
        (*parent)->zone_id = NULL;
    }

    delete (*parent);
    (*parent) = NULL;
}

这是结构:

struct node {

    int* zone_id;
    node* leaves [NUM_ELEMS];

    node() : leaves() {} //setting all leaves pointers to NULL

};

指针初始化(在其他函数中):

    (*parent)->leaves[value]->zone_id = new int;
    *((*parent)->leaves[value]->zone_id) = zone_id;

我只是看不出它失败的地方......

4

1 回答 1

0

试试看..我认为这个“如果”应该包括所有代码不仅递归destroy_tree

void Tree::destroy_tree(node** parent) 
{
if ( (*parent) != NULL )  //I think this "if" should be include all code Not only recursion destroy_tree
  {
    for (int i=0; i<NUM_ELEMS; i++) 
    {enter code here
        destroy_tree( &((*parent)->leaves[i]));
    }
   if ( (*parent)->zone_id != NULL )   //the (*parent) should not be NULL
    {
        delete (*parent)->zone_id;
        (*parent)->zone_id = NULL;
    }
    delete (*parent);  //the (*parent) should not be NULL
    (*parent) = NULL;
    }
}

对不起我糟糕的英语

于 2013-01-07T10:54:00.893 回答