插入 3 次后,将结构插入链表挂起

insertion of structs into linked list hangs after 3 insertions

我正在尝试在 C 中实现基本的上下文无关语法分析器。我对 C 还是很陌生,正在尝试解决问题。

我想解析以下格式的文件:

RULE LEFT_HAND_SIDE RIGHT_HAND_SIDE
RULE2 LEFT_HAND_SIDE RIGHT_HAND_SIDE
etc

这是我的代码:

  while(fscanf(fp, "%s %s %s\n", type, LHS, RHS) == 3){

      if(!strcmp(type, "RULE") || !strcmp(type, "rule")){

          if(rules->head == NULL && rules->tail == NULL){

              rules->head = malloc(sizeof(Rule));
              rules->head = &(Rule) { 
                  .LHS = LHS,
                  .RHS = RHS,
                  .condition = "",
                  .next = NULL
              }; 
              rules->tail = rules->head;
          }
          else{

              Rule *curr;
              curr = rules->head;

              while(curr->next){
                  curr = curr->next;
              }

              curr->next = malloc(sizeof(Rule));
              curr->next = &(Rule) { 
                  .LHS = LHS,
                  .RHS = RHS,
                  .condition = "",
                  .next = NULL
              }; 
              rules->tail = curr->next;
          }
      } 
  }

当我运行这个程序并输入一个包含7条规则的文件时,它在成功插入3条规则后停止向链表添加结构,并挂起。我不知道发生了什么,现在已经卡了几个小时了。

当您将数据分配给您的节点指针时:

    curr->next = malloc(sizeof(Rule));
    curr->next = &(Rule) { 
      .LHS = LHS,
      .RHS = RHS,
      .condition = "",
      .next = NULL
    }; 

你先分配内存,然后把指针赋给一个自动存储的本地对象的地址,也就是用复合字面量创建的对象。这意味着您会立即泄漏分配的内存,因为您失去了它的唯一句柄,并且一旦本地对象超出范围,您的指针可能会指向无效内存。 (稍后尝试 free 内存时会出错。)

如果你想用复合文字初始化新分配的,这样做:

    curr->next = malloc(sizeof(Rule));
    *curr->next = (Rule) { 
      .LHS = LHS,
      .RHS = RHS,
      .condition = "",
      .next = NULL
    }; 

这将创建一个本地对象并将其内容复制到 curr->next 指向的对象。