简体   繁体   English

链表的分段错误 - 仅在使用多个时

[英]Segmentation Fault with Linked List - only when using more than one

So I wrote a function to insert elements to the end of a linked list, which worked as intended.所以我写了一个 function 将元素插入到链表的末尾,它按预期工作。 Or so I thought till I tried using the same function for another list, which produced a segmentation error, and I can't figure out why.或者我想直到我尝试对另一个列表使用相同的 function,这会产生分段错误,我不知道为什么。 Forgive me if this isn't the best way to insert, I'm still learning.如果这不是最好的插入方式,请原谅我,我还在学习。

The Implementation:实施:

struct Node
{
    int data;
    struct Node* next;
};
typedef struct Node LL;

LL *makeNode(int data)
{
    LL *res = malloc(sizeof(LL));
    res->data = data;
    res->next = NULL;
    return res;
}

LL *insert(LL *head, int item)
{
    if(!head)
        return makeNode(item);
    else if(!head->next)
    {
        head->next = makeNode(item);
    }
    else
    {
        LL *tmp = head;
        while(tmp->next)
            tmp = tmp->next;
        tmp->next = makeNode(item);
    }
    return head;
}

void display(LL *head)
{
    if(!head)
    {
        printf("\n");
        return;
    }
    printf("%d, ", head->data);
    display(head->next);
}

Here's how I'm calling it in the main function:以下是我在主 function 中的称呼方式:

int main()
{
    srand(time(0));
    LL *head1, *head2;
    int i, n1 = 10, n2 = 10, item;
    for(i=0; i<n1; i++)
    {
        item = rand()%10;
        head1 = insert(head1, rand()%10);
    }
    for(i=0; i<n2; i++)
    {
        item = rand()%10;
        head2 = insert(head2, rand()%10);
    }
    display(head1);
    printf("2: ");
    display(head2);
}

The above piece of code provides the expected output when I test with LL head1 or LL head2 individually.当我单独使用 LL head1 或 LL head2 进行测试时,上面的代码提供了预期的 output。 But doing both at the same time causes the infamous segmentation fault and I'm not sure as to why.但是同时做这两个会导致臭名昭著的分段错误,我不确定为什么。 Any help would be appreciated, thanks in advance.任何帮助将不胜感激,在此先感谢。

Your insert() function creates the head node if one doesn't exist.如果头节点不存在,您的insert() function 会创建头节点。 This happens when you pass in a NULL pointer to insert() as the first parameter.当您将 NULL 指针作为第一个参数传递给 insert() 时,就会发生这种情况。 In your main function the head1 and head2 pointers are both automatic variables, so they will be undefined the first time you call insert().在您的主 function 中,head1 和 head2 指针都是自动变量,因此在您第一次调用 insert() 时它们将未定义。 You should change their declarations to:您应该将他们的声明更改为:

LL *head1 = NULL;
LL *head2 = NULL;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM