Reputation: 3
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.
Upvotes: 0
Views: 70
Reputation: 1714
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;
Upvotes: 1