插入AVL树时出错

时间:2013-12-02 20:45:32

标签: c++ avl-tree

我在插入AVL树时遇到错误。程序进入插入功能时崩溃。我正在从文本文件中读取一些文件名并将它们传递给这个insert_data函数,然后调用insert_node。这些是我的功能

void DataStructure::insert_data(char * &fileName, long int address)
{  
    this->root =  this->insert_node(this->root, fileName, address);
}


node * DataStructure::insert_node( node *t, char * &file_name, long int address)
    {
        if(t==NULL)
{
    t = new node;
    t->address = address;
    strcpy(t->buffer, file_name);
    t->height = 0;
    t->left = NULL;
    t->right = NULL;
}
else if(atoi(file_name) < atoi(t->buffer))
{
    t->left = insert_node(t->left, file_name, address);
    if(get_height(t->left) - get_height(t->right) == 2)
    {
        if(atoi(file_name) < atoi(t->left->buffer))
            t=SingleRotationLeft(t);
        else
            t=DoubleRotationLeft(t);
    }
}
else if( atoi(file_name) > atoi(t->buffer))
{
    t->right = insert_node(t->right, file_name, address);
    if(get_height(t->right) - get_height(t->left) == 2)
    {
        if(atoi(file_name) > atoi(t->right->buffer))
            t= SingleRotationRight(t);
        else
            t=DoubleRotationRight(t);
    }
}

t->height = max_height(get_height(t->left), get_height(t->right)) + 1;
return t;
}

我的构造函数是

DataStructure::DataStructure(void)
{
    root = NULL;
}

1 个答案:

答案 0 :(得分:0)

strcpy(t->buffer, file_name);

写入未初始化的指针。您需要为buffer分配内存。如果您使用与Posix兼容的系统,最简单的方法是使用strdup

t->buffer = strdup(file_name);

否则,您需要分配内存然后单独复制

t->buffer = malloc(strlen(file_name)+1);
strcpy(t->buffer, file_name);

在任何一种情况下,当您为每个free(t->buffer)释放内存时,您需要node