有人能告诉我段错误的原因吗 - 这个程序中的(核心转储)错误

标签 c segmentation-fault

谁能帮我解决程序中的段错误错误。 我最近开始使用链表,但我不知道我是否正确使用了 struct node。如果使用错误,有人可以纠正我。谢谢!

#include<stdio.h>
#include<stdlib.h>
struct node
{
        int data;
        struct node* link;
};
struct node* root = NULL;
void append()
{
        struct node* temp;
        temp=(struct node*)malloc(sizeof(struct node));
        printf("Enter The Node Value: ");
        scanf("%d",&temp->data);
        temp->link=NULL;
        if(root = NULL)
        {
                root = temp;
        }
        else
        {
                struct node* p;
                p = root;
                while(p->link != NULL)
                {
                        p=p->link;
                }
                p = temp;
        }
}
int main()
{
        printf("Add A Node To The Structure:-\n");
        while(1)
        {
                int ch;
                printf("Enter 2 To Exit\n");
                printf("Enter Your Choice:");
                scanf("%d",&ch);
                switch(ch)
                {
                        case 2: exit(0);
                        default:append();
                }
        }
        return 0;
}

最佳答案

if(root = NULL) 将 null 分配给 root 而不是检查。 Null 被转换为 bool 值 false,因此执行 else block 。 使用 root 属性假设它是非 null 会导致段错误。 改为编写 if(root == NULL)

关于有人能告诉我段错误的原因吗 - 这个程序中的(核心转储)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57016552/

相关文章:

c - 在 Raspberry PI 上用 C 从图像中读取 RGB 数据

c++ - 运行时检查失败 #2,同时使用 API 保存图像帧

c - 寻找数组中最大的子列表?

c - 如何在C中释放三维指针内存

c - 信号栈

c - 未知的段错误可能与内存分配有关

c - 为什么这段修改字符串的代码不起作用?

linux - 注释掉Printf导致段错误

c++ - 在 Linux x64 下使用 libmozjs-52 (SpiderMonkey) 的段错误

c++ - 在 C++ 中捕获 SIGSEGV 的成本