'Seg fault adding a node to linked list in c
In leetcode Add-Two-nums I am trying to loop over the two linked lists, in the first example I create a middle pointer to the allocated node and then add it to the original node, in the second example I try to get rid of this ptr variable and add the node directly but keep on getting a stack buffer overflow in leetcode for both examples and only a seg fault in the second example when compiling on my own machine the first example works fine
ListNode * addTwoNums(ListNode *l1, ListNode *l2)
{
ListNode *result;
ListNode *tmp = result;
int carry =0;
int sum =0;
while ( l1->next != NULL && l2->next != NULL)
{
sum = l1->val+l2->val+carry ;
printf("%d + %d = %d\n", l1->val, l2->val, l1->val+l2->val);
if ( sum > 9)
{
result->val = 0;
carry = 1;
}
else
{
result->val = sum;
carry = 0;
}
ListNode *ptr = (ListNode *)malloc(sizeof(ListNode));
result->next = ptr;
l1 = l1->next;
l2 = l2->next;
result = result->next;
}
}
In this example I remove the pointer ptr and try to add the allocated Node directly to the next value but I get a seg fault
ListNode * addTwoNums(ListNode *l1, ListNode *l2)
{
ListNode *result;
ListNode *tmp = result;
int carry =0;
int sum =0;
while ( l1->next != NULL && l2->next != NULL)
{
sum = l1->val+l2->val+carry ;
printf("%d + %d = %d\n", l1->val, l2->val, l1->val+l2->val);
if ( sum > 9)
{
result->val = 0;
carry = 1;
}
else
{
result->val = sum;
carry = 0;
}
result->next = (ListNode *)malloc(sizeof(ListNode));
l1 = l1->next;
l2 = l2->next;
result = result->next;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
