0

So I wrote a function to insert elements to the end of a linked list, which worked as intended. 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. 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:

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. 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.

user438383
  • 5,716
  • 8
  • 28
  • 43
  • 1
    In `main` you never initialize `head1` and `head2`. I suggest you read this: https://stackoverflow.com/questions/766893/how-do-i-modify-a-pointer-that-has-been-passed-into-a-function-in-c – Jabberwocky Nov 30 '21 at 12:31

1 Answers1

1

Your insert() function creates the head node if one doesn't exist. This happens when you pass in a NULL pointer to insert() as the first parameter. In your main function the head1 and head2 pointers are both automatic variables, so they will be undefined the first time you call insert(). You should change their declarations to:

LL *head1 = NULL;
LL *head2 = NULL;
mmixLinus
  • 1,646
  • 2
  • 11
  • 16
  • Oh my god... totally overlooked and for hours at that. Thank you soo much, it works now! Goddamn I hate myself – Mithran Kesavan Nov 30 '21 at 14:23
  • 1
    @MithranKesavan That's one of the pitfalls of programming, staring for ages at your code, but not seeing the obvious. Don't be too harsh on yourself : ) And welcome to stackoverflow! PS. Don't forget to set this as the accepted answer. Thanks. – mmixLinus Nov 30 '21 at 14:32
  • Thank you for the kind words, just marked it as the accepted answer! I really respect your friendliness and welcoming attitude, wishing you good luck all the way <3 – Mithran Kesavan Dec 01 '21 at 16:39