1

Using a dummy node to add the lesser node of list l1 and list l2. At the end returning the location pointing next to the dummy node to get the actual merged sorted list but getting a runtime load of address with insufficient space for an object of type struct ListNode at return dummyNode->next.

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
        if (l1 == NULL && l2 != NULL) {
                return l2;
        }
        if (l1 != NULL && l2 == NULL) {
                return l1;
        }
        struct ListNode *dummyNode = NULL;
        struct ListNode *head = NULL;

        dummyNode = (struct ListNode *)malloc(sizeof(struct ListNode *));
        head = dummyNode;

        while (l1 != NULL && l2 != NULL) {
                if (l1->val <= l2->val) {
                        head->next = l1;
                        l1 = l1->next;
                        head = head->next;
                }
                else {
                        head->next = l2;
                        l2 = l2->next;
                        head = head->next;
                }
        }
        if (l1 != NULL) {
                head->next = l1;
        }
        if (l2 != NULL) {
                head->next = l2;
        }    
        return dummyNode->next;
}


3
  • 1
    I think the malloc has wrong parameter - it should be sizeof(struct ListNode) instead of sizeof(struct ListNode *) Commented Jan 23, 2019 at 13:29
  • Please read this: How to Ask and then edit your question and provide a minimal reproducible example as well as minimum input that triggers the problem. Commented Jan 23, 2019 at 13:29
  • Complement to 1st comment: instead of dummyNode = (struct ListNode *)malloc(sizeof(struct ListNode)); write dummyNode = (struct ListNode *)malloc(sizeof(*dummyNode)); which is less error prone. You even can drop the cast : dummyNode = malloc(sizeof(*dummyNode)); Commented Jan 23, 2019 at 13:31

1 Answer 1

2

Insufficient space is allocated because of passing to malloc sizeof pointer to structure sizeof(struct ListNode *). It should be changed to allocating space for whole structure -

dummyNode = (struct ListNode *)malloc(sizeof(struct ListNode));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.