C 将元素插入链表时出现分段错误(核心转储)

C 将元素插入链表时出现分段错误(核心转储),c,C,我不熟悉数据结构,我正在尝试实现一个链表数据结构。我在运行时遇到“分段错误(内核转储)” 我正在使用Linux终端编译和运行程序。我编写了一个insert\u element()函数来在开头插入一个节点,并编写了一个递归函数print()来打印列表。我在运行时遇到分段错误。我怎样才能摆脱它 struct node{ int data; struct node* link; }; struct node* insert_element(struct node* A

我不熟悉数据结构,我正在尝试实现一个链表数据结构。我在运行时遇到“分段错误(内核转储)”

我正在使用Linux终端编译和运行程序。我编写了一个
insert\u element()
函数来在开头插入一个节点,并编写了一个递归函数
print()
来打印列表。我在运行时遇到分段错误。我怎样才能摆脱它

struct node{
        int data;
        struct node* link;
};

struct node* insert_element(struct node* A,int ino)
{
        struct node *temp=(struct node*)malloc(sizeof(struct node));
        temp->data=ino;
        temp->link=NULL;
        if(A=NULL)
        {
        A=temp;
        }
        else
        {
                struct node* temp1=A;
                while(temp1->link!=NULL)
                {
                        temp1=temp1->link;
                }
                temp1->link=temp;
        }
        return A;
}

void print(struct node* ptr)
{
        if(ptr==NULL)
                return;
        printf("%d",ptr->data);
        print(ptr->link);
}

int main()
{
        struct node* head=NULL;
        head=insert_element(head,5);
        head=insert_element(head,5);
        head=insert_element(head,6);
        head=insert_element(head,3);
        head=insert_element(head,5);
        print(head);
        return 0;
}

您有一个
a=NULL
,其中应该有一个
a==NULL
。现在,您正在将
A
设置为
NULL
,然后尝试访问它的一个字段

在C语言中,赋值运算符(
=
)返回它所赋值的值。因此,当您说
if(A=NULL)
时,它将
NULL
分配给
A
,然后返回
NULL
,因此条件为false,执行
else
分支

else {
    struct node* temp1 = A; // now temp1 is also NULL
    while (temp1->link != NULL) // temp1 is NULL, so this is NULL->link
因此,您最终得到的是
NULL->link
,它试图取消引用
NULL
,这是一种未定义的行为,通常会导致segfault

如果使用
gcc
进行编译,我建议使用
-Wall
(甚至可能使用
-Wextra
)来显示更多编译警告,包括在条件表达式中使用
=
的警告


如果您想知道为什么C允许这样做,那么它对于检查函数调用的结果非常有用。例如:

if ((char *buffer = malloc(100))) {
    // malloc worked, and you can use the buffer here
}
else {
    // malloc failed, so you can do something else
}

使用一些有用的标志编译程序会帮助您解决问题:

user@machine:~$ gcc -Wall -Werror -o scratch main.c
main.c: In function ‘insert_element’:
main.c:14:12: error: suggest parentheses around assignment used as truth value [-Werror=parentheses]
         if(A=NULL)
            ^
cc1: all warnings being treated as errors
如果不解决此问题,您将

user@machine:~$ gcc -o scratch main.c
user@machine:~$ ./scratch 
Segmentation fault (core dumped)
如果我们修正了错误

if(A==NULL)
并更改
printf
语句

printf("%d\n",ptr->data);
我们得到这个输出

5
5
6
3
5

您的标题引用了“未知类型错误”。这只能作为编译时错误在C中发生。如果你有那个错误,你的程序将无法运行,你也无法得到分段错误。@KeithThompson,当OP说“未知类型错误”时,他显然没有引用错误消息,而是说他不知道自己是哪种错误seeing@jirassimok先生,我对你所说的-沃尔和-韦斯特拉一点线索也没有。。所以请告诉我更多关于它的信息,谢谢你的帮助。@HAL9000:这不太明显,但标题现在已经编辑好了,所以没关系。@jirassimok我不理解你最后一次评论背后的概念如果((char*buffer==malloc(100)){}else{}。请解释一下。。。