Home > database >  Same output when printing out a tree in C
Same output when printing out a tree in C

Time:07-25

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?

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.

CodePudding user response:

As MikeCAT explained, each new node needs to preserve its own discrete key.

main() can be greatly simplified. Here the max key length must be < 128.

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

    for( ;; ) {
        char str[128];

        if( scanf( "%s", str ) == 1 ) {
            if( strcmp( str, "#end" ) == 0 )
                break;
            root = insert( root, str );
        }
    }
    printTree(root);
}

and strdup() can be used to preserve the key for the new node.

Node* newNode( char *key ) {
    Node *tmp = (Node*)malloc( sizeof(Node) );
    tmp->key = strdup( key );
    tmp->sx = tmp->dx = NULL;
    return tmp;
}
  • Related