【问题标题】:Error while inserting into an AVL tree插入 AVL 树时出错
【发布时间】:2013-12-03 05:01:52
【问题描述】:

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

【问题讨论】:

  • strcpy(t-&gt;buffer, file_name); 这似乎是错误的。 t->buffer的大小是多少?
  • node 是如何定义的?具体来说,bufferchar 数组还是只是一个指针?
  • node 是一个结构体 struct node{ char * buffer;长整数地址 }

标签: c++ avl-tree


【解决方案1】:
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);

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

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    相关资源
    最近更新 更多