0

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.

Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
chickenman
  • 728
  • 2
  • 9
  • 29

1 Answers1

2

There is a problem with malloc(going->strlen)+100. You are getting an address from the heap with malloc() then adding 100 to that address for some reason, and explicitly casting it to force it to work. (I suggest looking at Do I cast the result of malloc?.) Such pointer arithmetic doesn't make sense. This will surely cause you to read or write in the wrong place later, causing a segfault.

Instead of guessing what an appropriate string allocation size should be, keep track of how big it is, and expand it as needed (see realloc()).

Community
  • 1
  • 1
e0k
  • 6,961
  • 2
  • 23
  • 30