2016-12-04 3 views
0

ランダムツリージェネレータがあり、子トラバーサルに基づいてツリーの値を連結する必要があります。私はこのコードのブロックの終わりまでにCでのツリーのトラバーサルと連結のクラッシュ

com ----- org------net--- 
      | 
      mom---dad---son 
         | 
         good 

私は、文字列を望む「goodsonorg」

struct trie_node *going = root; // this gets the root of the tree 
char* joiner = NULL;    //using this to join the previous part 

char *lastOne = (char *)(malloc(going->strlen+1000)); //setting safe buffer 

while(going->next != NULL || going->children != NULL) { 

    while(going->next){   // always go as right as possible 
     going = going->next; 
    } 

    if(going->children){  //traverse down to child 

     if(joiner == NULL) { // traverse from root (previous will be null) 

      printf(" first key is: \n"); 
      joiner = (char *)(malloc(going->strlen)+100); 
      strncpy(joiner,going->key, going->strlen+1);  
      puts(joiner); 
     } 

     else{ 
      printf(" \n We need to concatenate: \n"); 
      going = going->children; // go down 

      strncpy(lastOne, going->key, going->strlen); // get the current key in last 
      puts(lastOne); 
      printf(" with the previous one to get: \n "); 
      strcat(lastOne, joiner); // attach the joiner to it. 

      strncpy(joiner, lastOne, strlen(joiner)+strlen(lastOne)); // then update the joiner 
      puts(lastOne); 
      } 

を持っている場合たとえば、私はlastOneの私の連結文字列を持っている必要があり、しかし、私はのためのセグメンテーションフォルトを取得何らかの理由で。なぜ私は分からない。私はreallocが私にエラーを与えていたので、安全なビッグバグを割り当てています。私がここで紛失していることは明らかですか?木の巡回は間違いなく機能します。

+0

[正しいC書式設定](// prohackr112.tk/r/proper-c-formatting)を調べてください。あるいは、コードを徹底的に難読化する方法を学んでください(// prohackr112.tk/r/proper-c-obfuscation)。 –

+0

コピー貼り付けでフォーマットがうまくいきませんでした – qaispak

+1

いずれにしても、適切な書式設定は、あなたの質問に人々を引きつけ、彼らがあなたを助けるよう励まします。 –

答えて

2

malloc(going->strlen)+100に問題があります。ヒープからアドレスmalloc()を取得していて、なんらかの理由でそのアドレスに100を追加し、それを強制的に動作させるために明示的にキャストします。 (私はDo I cast the result of malloc?を見てみることをお勧めします)。そのようなポインタ算術は意味をなさない。これにより、間違った場所で後で読み書きが行われ、セグメンテーションが発生します。

適切な文字列割り当てサイズを推測する代わりに、その大きさを把握し、必要に応じて展開します(realloc()参照)。

関連する問題