Search code examples
cstringwhile-loopc-strings

Same output when printing out a tree in C


struct Node{
  char *key;
  struct Node *sx, *dx;
};

typedef struct Node Node;

int main(void){
  Node *root = NULL;

  char *str = malloc(sizeof(char)*5);

  if(scanf("%s", str) == 1) root = insert(root, str);

  while(strcmp(str, "#end") != 0){
    if(scanf("%s", str) == 1)
      if(strcmp(str, "#end") != 0) insert(root, str);
      else break;
    else printf("error\n");
  }

  printTree(root);
}

I have a BST with the key as a string, and I want to insert multiple strings in the tree, but when I print the tree with the printTree function, print only "#end" many times as the number of strings I inserted.

Here it is an example Output:

$ ./out
hi
all
how 
are
you
#end
#end
#end
#end
#end
#end

The values I type go into the tree (checked with a search algorithm), so I expect the differents value when the tree is printed.

Does anyone knows how to solve it?


Solution

  • You have to allocate a buffer for each strings instead of allocating only one buffer and reusing (overwriting with new strings) that.

      while(strcmp(str, "#end") != 0){
        str = malloc(sizeof(char)*5); // add this here to allocate new buffer for new string
        if(scanf("%4s", str) == 1)
          if(strcmp(str, "#end") != 0) insert(root, str);
          else break;
        else printf("error\n");
      }
    

    Also you should use %4s (in this case) instead of %s for scanf() to limit the number of characters to read and avoid buffer overrun.