简体   繁体   English

打印答案时出现分段错误

[英]Segmentation Fault when printing answer

I am just getting some practice in with trees, and can't figure out why I keep getting a seg fault when I try to insert a vcard into my binary search tree... Any help? 我只是在树上进行一些练习,无法弄清楚为什么在尝试将vcard插入二进制搜索树时仍然出现段错误...有什么帮助吗? Thanks. 谢谢。 I have attached the function, and some tests that I used to run the function. 我已经附加了该功能,以及一些我用来运行该功能的测试。 For some reason, it works for one case (when i match ID2 with the bst), but does not work when I try to match ID1 with the bst. 出于某种原因,它仅在一种情况下有效(当我将ID2与bst匹配时),但在我尝试将ID1与bst匹配时不起作用。

Thank you! 谢谢!

typedef struct {
  char *cnet;
  char *email;
  char *fname;
  char *lname;
  char *tel;
} vcard;

typedef struct bst bst;
struct bst {
  vcard *c;
  bst *lsub;
  bst *rsub;
};

 int bst_insert(bst *t, vcard *c) {

  if (t->c == NULL) {
    fprintf (stderr, "Empty vcard");
  }
  if (strcmp(c->cnet,t->c->cnet) == 0) {
    return 0;
  }
  else if ((strcmp(c->cnet,t->c->cnet) < 0) && (t->lsub == NULL)) {
    t->lsub->c = c;
    return 1;
  }
  else if ((strcmp(c->cnet, t->c->cnet) < 0) && (t->lsub != NULL)) {
    bst_insert(t->lsub, c);
  }
  else if ((strcmp(c->cnet, t->c->cnet) > 0) && (t->rsub == NULL)) {
    t->rsub->c = c;
    return 1;
  }
  else if ((strcmp(c->cnet, t->c->cnet) > 0) && (t->rsub != NULL)) {
    bst_insert(t->rsub, c);
  }

}

int main () {
  vcard  NewID;
  NewID.cnet = "leeholim";
  NewID.email = "leeholim@uchicago.edu";
  NewID.fname = "leeho";
  NewID.lname = "lim";
  NewID.tel = "555-555-5555";


  vcard  NewID2;
  NewID2.cnet = "donalfonsodailey";
  NewID2.email = "ddailey@gmail.com";
  NewID2.fname = "My name's donny";
  NewID2.lname = "dailey";
  NewID2.tel = "212-323-1234";


  bst ID;
  ID.c = &NewID;
  ID.lsub = NULL;
  ID.rsub = NULL;

  printf("%s\n", Poop->c->fname);
  printf("%d\n", bst_insert(&ID, &NewID2));
}
else if ((strcmp(c->cnet,t->c->cnet) < 0) && (t->lsub == NULL)) {
  t->lsub->c = c;
  return 1;
}

Definitely you should not assign t->lsub->c when t->lsub == NULL . t->lsub == NULL时,绝对不应该分配t->lsub->c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM