There is a random tree generator and I have to concatenate the values of the tree based on child traversals. For example if I have
com ----- org------net---
|
mom---dad---son
|
good
I would want the string "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);
}
By the end of this block of code I should have my concatenated string in lastOne, however I get a segfault for some reason. I am not sure why. I am allocating safe big buggers because realloc was giving me errors. Is there anything obvious that I am missing here? The tree traversal definitely works.