Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Same output when printing out a tree in C11

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Does anyone knows how to solve it?

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

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading