0
我刚开始编程,并有一个初学者的问题,我正在写一个trie插入函数,它将一个字符串插入到树中。但是,当我添加一个字符串超过两个字符时,我得到堆缓冲区溢出。这里是我的插入功能:C编程树树插入
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 [3] = '\ 0';? – woshidashen
并分配内存,它是否假设为struct node * root =(struct node *)malloc(sizeof(struct node)); 取而代之? – woshidashen
@GhostKidYao 1.是的,但为什么不'char * c =“ade”;',因为'c'是只读的? 2.是的。 – zzn