【问题标题】:C programming trie tree insertC编程特里树插入
【发布时间】:2017-02-23 03:33:20
【问题描述】:

我刚开始编程并且有一个初学者问题,我正在编写一个 trie 插入函数,它将一个字符串插入到 trie 树中。但是当我添加一个超过两个字符的字符串时,我会遇到堆缓冲区溢出。这是我的插入函数:

struct node* insert(struct node *root,char *c){
int i=0;
struct node *temp=root;
while(c[i]){
int index=c[i]-'a';
//New Node
struct node *n=malloc(sizeof(*n));
n=malloc(sizeof(struct node));
temp->child[index]=n;
i++;
temp=temp->child[index];
}
return root;
};

树节点的定义

struct node
{   
int isword;
int prefix;
int occurrence;
int leaf;
struct node * child[26];
};

以及我如何称呼他们

char *c=malloc(3*sizeof(char));
c[0]='a';
c[1]='d';
c[2]='e';
struct node *root=malloc(sizeof(*root));
root=malloc(sizeof(struct node));
insert(root,c);

我认为这是我在插入函数中为出错的新节点分配空间的方式,但我不确定避免堆缓冲区溢出的正确方法是什么,请给点建议?

【问题讨论】:

    标签: c tree insert trie


    【解决方案1】:

    c 不以 nul 结尾。所以如果i>=3(可能是coredump,因为访问无效的内存地址),c[i] 是未定义的。 while(c[i]) 可能会运行 3 次以上。这也许是重点。

    char *c=malloc(3*sizeof(char));
    c[0]='a';
    c[1]='d';
    c[2]='e';
    

    顺便说一句,下面的代码会导致内存泄漏:

    struct node *root=malloc(sizeof(*root));
    root=malloc(sizeof(struct node));
    

    【讨论】:

    • 所以我应该做类似 c[3]='\0';?
    • 对于分配内存,是否假设为 struct node * root = (struct node *)malloc(sizeof(struct node));代替?
    • @GhostKidYao 1. 是的,但为什么不是char *c="ade";,因为c 是只读的? 2. 是的。
    • 谢谢! 1.因为我想逐个字符地文件以确保它是字母并将其添加到字符串中。所以我得一一添加。
    • @GhostKidYao 那么您可以接受将这个问题标记为已解决的答案,因为它可能对其他人有所帮助。
    猜你喜欢
    • 2021-05-01
    • 2015-06-16
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2013-06-12
    相关资源
    最近更新 更多