c - 在 ubuntu 中执行程序时出现 C 段错误

标签 c ubuntu segmentation-fault

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *next;
};
struct node *head;
void insert(int a)
{
    struct node* temp=(struct node*)malloc(sizeof(struct node));
    struct node* temp1;
    if(head=NULL)
    {
        temp->data=a;
        temp->next=NULL;
        head=temp;
        return;
    }
    {
        temp1=head;
        temp->data=a;
        while(temp1->next!=NULL)
        {
            temp1->next=temp;
        }
    }
}
void print()
{
    struct node* temp2;
    temp2=head;
    while(temp2->data!=NULL)
    {
        printf("the data are %d",temp2->data);
    }
}
int main()
{
    int n,a,i;
    printf("how many number");
    scanf("%d",&n);
    head=NULL;
    for(i=0;i<=n;i++)
    {
        printf("enter the no. to store");
        scanf("%d",&a);
        insert(a);
        print();
    }
}

我不知道这个程序有什么问题。每次我尝试编译此程序时,都会发生错误:“段错误(核心转储)”。我正在 Ubuntu 上做这个程序。段错误是什么意思以及如何修复它?

最佳答案

也许下次你应该使用调试器。

  #include<stdio.h>
  #include<stdlib.h>
  struct node
  {
      int data;
      struct node *next;
  };
  struct node *head;
  void insert(int a)
  {
>     struct node* temp=malloc(sizeof(struct node));
      struct node* temp1;
>     if(head==NULL)
      {
          temp->data=a;
          temp->next=NULL;
          head=temp;
          return;
      }
>     else
      {
          temp1=head;
          temp->data=a;
>         temp->next=NULL;
          while(temp1->next!=NULL)
          {
>             temp1=temp1->next;
          }
>         temp1->next=temp;
      }
  }
  void print()
  {
      struct node* temp2;
      temp2=head;
>     while(temp2!=NULL)
      {
          printf("the data are %d",temp2->data);
>         temp2=temp2->next;
      }
  }
  int main()
  {
      int n,a,i;
      printf("how many number");
      scanf("%d",&n);
      head=NULL;
>     for(i=0;i<n;i++)
      {
          printf("enter the no. to store");
          scanf("%d",&a);
          insert(a);
          print();
      }
  }

关于c - 在 ubuntu 中执行程序时出现 C 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45725247/

相关文章:

c - 将标准错误重定向到 C 中的字符串

Java 与 C 运行时(REPOST)

ubuntu - 在 Ubuntu 上构建的 Dotnet 返回代码 1

ubuntu - 与原生 Windows NPM/Yarn 处理相比,为什么 WSL 非常慢?

python - zlib 和 PYTHONPATH 的 Linux Mint 9 Virtualenv ImportError 为空?

c - 使用 malloc 创建的结构体设置值的段错误

c - 释放无关数据时出现段错误

c - 理清 .h 依赖项

c++ - C/C++ 中的类型转换到底是什么?

c - 段错误 - 使用 librsync 库时