【问题标题】:Runtime Error :member access within misaligned address in C programming in linked list运行时错误:链表中 C 编程中未对齐地址内的成员访问
【发布时间】:2022-11-11 02:23:13
【问题描述】:
Line 70: Char 15: runtime error: member access within misaligned address 0x7fc00000000c for type 'struct ListNode', which requires 8 byte alignment [ListNode.c]
0x7fc00000000c: note: pointer points here
<memory cannot be printed>

我刚刚在 leetcode.com 的程序中遇到了这个错误 为什么它不起作用?我尝试使用合并两个列表的第一个算法来合并 k 个列表,该算法经过测试并且正确!请对我的问题有任何解释吗?

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
    if (list1==NULL && list2==NULL)
        return NULL;
    struct ListNode head  ;
    struct ListNode *result = &head;
    while (list1 && list2) {
       if (list1->val < list2->val) {
           result->next=list1;
           list1=list1->next;
           result = result->next;
       }
       else {
           result->next=list2;
           list2=list2->next;
           result = result->next;
       }
    }
    if (list1) {
        result->next=list1;//????????????????????????????????????
    }
    if (list2) {
        result->next=list2;
    }
    return head.next;
}

struct ListNode* mergeKLists(struct ListNode** lists, int listsSize)
{
   struct ListNode head;
   struct ListNode *result = &head;
   result=mergeTwoLists(lists[0],lists[1]);
   for (int i = 2; i<listsSize; i++) {
       result=mergeTwoLists(result,lists[i]);
   }
   return head.next;
}

我想知道这个错误的原因。

【问题讨论】:

  • 请不要转储如此难以理解的一堆测试。应用适当的压痕。也不要在一行中编写多条指令。仅当您讨厌阅读您的代码的人时才这样做。
  • mergeKLists 中,您似乎没有初始化head 的字段。
  • 特别是,mergeKLists 中的任何代码都没有对对象head 做任何事情,除了最后一行返回其next 成员中的任何垃圾。您首先将result 指向head,但在下一行覆盖之前,您从未对result 进行任何操作。 result = ... 仅更改指针并且对它的对象什么也不做指着.
  • 询问代码中的错误的问题通常需要提供minimal reproducible example。这是不可重现的,因为它没有标题、main 函数等,所以如果没有大量额外的工作和猜测如何填充这些部分,就无法编译和测试它。

标签: c linked-list


【解决方案1】:

您的 mergeKLists 函数存在一些问题:

  • 该代码假定至少给出了 2 个列表,但可能只有一个列表,甚至没有。请注意代码质询描述中k 的范围。如果 k 为 0 或 1,您将为 mergeTwoLists 提供未定义的引用,从而导致您遇到的错误

  • return head.next 返回一个未初始化的值,因为 head 仅被声明然后被忽略。

  • 赋值*result = &amp;head 没有用,因为result 在下一条语句中被新值覆盖。

这是一个更正:

struct ListNode* mergeKLists(struct ListNode** lists, int listsSize)
{
    if (listsSize == 0) return NULL; // Boundary case: no lists
    struct ListNode *result = lists[0]; // We are sure there is this first list
    for (int i = 1; i<listsSize; i++) {
        result=mergeTwoLists(result,lists[i]);
    }
    return result;
}

【讨论】:

    猜你喜欢
    • 2017-12-29
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    相关资源
    最近更新 更多