2017-02-23 63 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