【问题标题】:Why do I have a segmentation fault in my link list?为什么我的链接列表中有分段错误?
【发布时间】:2021-02-14 04:50:03
【问题描述】:

在我输入第一个数字后,它显示分段错误,我不知道为什么。我的目标是制作一个链接列表,其中我有一个特定数字的根,并会输入更大的数字,这些数字最终将被添加到链接列表的一部分中。例如,根/第一个数字将是 50。我将添加一个更大的数字 60,它将添加到 lin 列表下方的另一个节点。这个过程会重复,因为我假设输入的数字会越来越大。

#include <stdio.h>
#include <stdlib.h>

typedef struct node{

  int num;
  struct node* left;
  struct node* right;

}
node;

int main(void){

  printf("Put in a number:");
  int x = 0;
  scanf("%i", x);

  node* a = malloc(sizeof(node));
  a->num = x;
  node* temp = a;

  int n = 1;
  while(n == 1){
    
    printf("Put in another number:");
    int y = 0;
    scanf("%i", y);

    while(n == 1){
      
      if (temp->num < y){
        if (temp->right == NULL){
          node* a = malloc(sizeof(node));
          temp->right = a;
          temp->right->num = y;
          break;
        }
        else{
          temp = temp->right;
        }
      }
    
    printf("Want to stop? Yes(1) or No (1)?");
    scanf("%i", n);
    
    }
  } 
}

【问题讨论】:

    标签: c while-loop linked-list segmentation-fault singly-linked-list


    【解决方案1】:

    scanf 调用的参数

    scanf("%i", x);
    scanf("%i", y);
    scanf("%i", n);
    

    不正确。您必须通过引用传递变量

    scanf("%i", &x);
    scanf("%i", &y);
    scanf("%i", &n);
    

    这个while循环

    while(n == 1){
      
      if (temp->num < y){
        if (temp->right == NULL){
          node* a = malloc(sizeof(node));
          temp->right = a;
          temp->right->num = y;
          break;
        }
        else{
          temp = temp->right;
        }
      }
    
    printf("Want to stop? Yes(1) or No (1)?");
    scanf("%i", n);
    
    }
    

    可以调用未定义的行为,因为对于新分配的节点

        if (temp->right == NULL){
          node* a = malloc(sizeof(node));
          temp->right = a;
          temp->right->num = y;
          break;
        }
    

    您没有将其数据成员 right 设置为 NULL。所以它具有不确定的价值。结果这个 if 语句

        if (temp->right == NULL){
    

    在这句话之后

          temp = temp->right;
    

    将此不确定值与NULL 进行比较。

    而且输出的字符串好像有错别字

    printf("Want to stop? Yes(1) or No (1)?");
                            ^^^^       ^^^
    

    【讨论】:

      【解决方案2】:

      您的问题可能会避免在编译器中启用警告(-Wall 用于 GCC)。 始终检查警告,即使编译似乎仍在进行(可以通过-W error 避免)。

      通过调用scanf (),您对您的程序说:“从stdin 读取输入,如果它与我定义的格式说明符匹配,则将其存储到特定地址”。。 p>

      所以基本上它希望你传递给它的每个格式说明符都有一个地址。

      scanf("%i", x);
      

      您正在传递x,这不是地址,因此scanf尝试在那里写入导致分段错误,因为它可能是无效的地址,不属于操作系统分配给您的进程的

      您想要传递x的地址,使用一元运算符&amp;

      scanf("%i", &x);
      

      (当您为yn 变量调用scanf 时会重复同样的错误)

      【讨论】:

      • 是的,你已经得到我的点头,所以我被淘汰了。可能值得找出正在使用的编译器。然后我们可以展示如何启用警告,例如-Wall -Wextra -pedantic 到您的 gcc/clang/W3 用于 VS 等。
      • @DavidC.Rankin 实际上我的猜测是显示了衰减但忽略了
      • 老“牵马下水,不能让他喝水”问题:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 2011-01-26
      相关资源
      最近更新 更多