字符串BST中的分段错误

时间:2013-11-22 05:28:06

标签: c string segmentation-fault binary-search-tree

所以,我正在为大学里的一个班做作业,目的是构建一个读取文本的字符串BST,将其划分并在树中插入每个单词。

但是当我尝试插入一个单词(手动)时,我遇到了分段错误,你们可以告诉我我做错了什么并建议修理吗?

/* Structure for the node */
typedef struct node {
  char *key;
  int multi;
  struct node *left, *right;
} node;

node *root;

void Insert(char *x, node *p){
    p = root;

  /* if the pointer points to null, create a new node and insert the key */
  if (*p == NULL){
    (*p) = (node)malloc(sizeof(node))
    (*p)->key = strcpy((*p)->key, x);
    (*p)->left = NULL;
    (*p)->right = NULL;
    return;
  }
  else if (strcasecmp(x, p->key) < 0)
  { 
    Insert(x, &p->left);
    return;
  }

  else if (strcasecmp(x, p->key) > 0)
  {
    Insert(x, &p->right);
    return;
  }
  /* if the words are equal, add 1 to the multi (how many times the word appears */
  else
    (*p)->multi = multi + 1;
}

1 个答案:

答案 0 :(得分:0)

这是有问题的陈述:(*p)->key = strcpy((*p)->key, x);您仅为node分配了内存,但指针key仍然未初始化。您还需要为key分配内存,例如(*p)->key = malloc(strlen(x) + 1);