c - 在编写用于合并两个已排序链表的代码时获取地址错误的运行时负载

标签 c data-structures linked-list

使用虚拟节点添加列表 l1 和列表 l2 的较小节点。最后返回指向虚拟节点旁边的位置以获取实际的合并排序列表,但在返回 dummyNode->next 时获取地址的运行时负载,其中空间不足以容纳 struct ListNode 类型的对象。

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


最佳答案

由于传递给 malloc sizeof 指向结构 sizeof(struct ListNode *) 的指针,分配的空间不足。 应该改为为整个结构分配空间 -

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

关于c - 在编写用于合并两个已排序链表的代码时获取地址错误的运行时负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54328192/

相关文章:

algorithm - 从左列到右列的路径的最大总和

c - "context"这个词在结构中通常是什么意思?

c - 创建指向链表节点的指针时,malloc 和不使用 malloc 有什么区别?

c - 添加到 from 目录的链表数组

c - "incompatible type for argument 1 of ‘strcpy’ “C 中的错误

c - fwrite 函数在 wine 中运行时导致异常

sql - 用于管理键值存储中的时态数据的资源或工具是什么?

c - C 中删除列表节点的这一段是什么意思

c - 从二进制文件 c 构建一个 float

c - 身份属性的位操作