Home > Back-end >  Same output when printing out a tree in C11
Same output when printing out a tree in C11

Time:07-22

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

typedef struct Node Node;

int main(void){
  Node *root = NULL;
  //node->dx = newNode(3);

  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);
}

Node* newNode(char* i){
  Node *tmp = (Node*) malloc(sizeof(Node));
  tmp->key = i;
  tmp->sx = tmp->dx = NULL;

  return tmp;
}

void printTree(Node *node){
  if(node != NULL){
    printTree(node->sx);
    printf("%s\n", node->key);
    printTree(node->dx);
  }
}

Node* insert(Node *root, char* i){
  if(root == NULL) return newNode(i);
  else{
    if(strcmp(i, root->key) < 0) root->sx = insert(root->sx, i);
    else root->dx = insert(root->dx, i);
  }

  return 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?

PS. I'm using Ubuntu 20.04 with WSL on W10Home 21H2

CodePudding user response:

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.

  • Related