2017-02-23 58 views
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); 

我认为这是我如何插入函数分配空间新节点出错了,但我不确定什么是避免堆缓冲区溢出的正确方法,请指教?

回答

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)); 
+0

所以我应该这样做C [3] = '\ 0';? – woshidashen

+0

并分配内存,它是否假设为struct node * root =(struct node *)malloc(sizeof(struct node)); 取而代之? – woshidashen

+0

@GhostKidYao 1.是的,但为什么不'char * c =“ade”;',因为'c'是只读的? 2.是的。 – zzn