Home > Back-end >  Seg fault adding a node to linked list in c
Seg fault adding a node to linked list in c

Time:02-19

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;
    } 
}

CodePudding user response:

For starters this while loop

while ( l1->next != NULL && l2->next != NULL)

can already invoke undefined behavior if at least one of the passed lists is empty.

The pointer result is uninitialized

ListNode *result;

So at least this statement

result->val = 0;

also invokes undefined behavior.

And setting the data member val to 0 in any case does not make a sense.

Pay attention to that after the while loop one of the passed pointers can be a non-null pointer. You need also to process it after the while loop.

  • Related