zoukankan      html  css  js  c++  java
  • member access within misaligned address 0x0000002c3931 for type 'struct ListNode‘

    From MWeb

    在做leetcode 第2题时使用C语言编写链表时报错

    错误复现

    报错时的代码如下

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
       
        if(l1==NULL) return l2;
        if(l2==NULL) return l1;
         
        struct ListNode* result=(struct ListNode*)malloc(sizeof(struct ListNode));
        int tmp=l1->val+l2->val;
        if(tmp<10){
            result->val = tmp;
            result->next = addTwoNumbers(l1->next,l2->next);
        }else{
            result->val = tmp%10;
            struct ListNode* tmpN=(struct ListNode*)malloc(sizeof(struct ListNode));
            tmpN->val=tmp/10;
            result->next = addTwoNumbers(addTwoNumbers(l1->next,l2->next),tmpN); 
        }
        return result;
    }
    

    运行后报错

    member access within misaligned address 0x000000000e91 for type 'struct ListNode', which requires 8 byte alignment (ListNode.c)
    0x000000000e91: note: pointer points here
    

    错误原因

    在程序倒数第6行处申请了一个tmpN指向的结构体ListNode空间,而该结构体中包含next指针,若该节点作为整个链表的最后一个节点,如l1l2分别指向[5][6]时,此时tmpN指向的空间并没有初始化next指针,因此报错。

    解决办法

    使用NULL初始化next指针指向的内容,如

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
       
        if(l1==NULL) return l2;
        if(l2==NULL) return l1; 
        struct ListNode* result=(struct ListNode*)malloc(sizeof(struct ListNode));
        int tmp=l1->val+l2->val;
        if(tmp<10){
            result->val = tmp;
            result->next = addTwoNumbers(l1->next,l2->next);
        }else{
            result->val = tmp%10;
            struct ListNode* tmpN=(struct ListNode*)malloc(sizeof(struct ListNode));
            tmpN->next=NULL;
            tmpN->val=tmp/10;
            result->next = addTwoNumbers(addTwoNumbers(l1->next,l2->next),tmpN);   
        }
        return result;
    }
    

    By JZ
    Less is more

  • 相关阅读:
    树链剖分( 洛谷P3384 )
    ZJOI 2015 诸神眷顾的幻想乡
    BZOJ 1002 [FJOI2007]轮状病毒
    洛谷 P1485 火枪打怪
    Luogu2860 [USACO06JAN]冗余路径Redundant Paths
    CF962F Simple Cycles Edges
    Luogu3605 [USACO17JAN]Promotion Counting晋升者计数
    Luogu2295 MICE
    CF341D Iahub and Xors
    CF617E XOR and Favorite Number
  • 原文地址:https://www.cnblogs.com/joelz/p/member-access-within-misaligned-address-0x0000002c.html
Copyright © 2011-2022 走看看