【发布时间】: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);
我认为这是我在插入函数中为出错的新节点分配空间的方式,但我不确定避免堆缓冲区溢出的正确方法是什么,请给点建议?
【问题讨论】: