c++ - malloc在leetcode在线编译中出现内存对齐错误?vs15中调试正常,调试后替换malloc为new则恢复正常?
高洛峰
高洛峰 2017-04-17 15:21:47
0
1
772
reference binding to misaligned address 0x00000001ddb1 for type 'const int',

https://leetcode.com/problems...
题的链接

以下是代码

  ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int i = 1, v1 = 0, v2 = 0;
        ListNode begin(0);
        begin.next = NULL;
        ListNode *Tag = &begin;
        bool rouding = false;
        while (true)
        {
            if (l1 == NULL&&l2==NULL&&rouding!=true)
            {
                break;
            }
            int value = (l1 == NULL ? 0 : l1->val) + (l2 == NULL ? 0 : l2->val);
            if (rouding)
            {
                value += 1;
                rouding = false;
            }
            if (value >= 10)
            {
                rouding = true;
                value = value % 10;
            }
            //new部分
            ListNode *v;
            v = new ListNode(value);
       
            //malloc部分  (报错)
            ListNode *v = NULL;
            v = (ListNode *)malloc(sizeof(v));
            v->val = value;
            v->next = NULL; //此操作也是在线编译报错错误如下
            // store to address 0x000000a7de78 with insufficient space for an object of type 'struct ListNode *'
         
            
            Tag->next = v;
            Tag = Tag->next;
            l1 = l1==NULL?NULL:l1->next;
            l2 = l2==NULL?NULL:l2->next;
        }
        return begin.next;
    }
   
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
迷茫

Replace sizeof(v) with sizeof(*v).
v is a pointer, not an object. sizeof(v) returns the size of the next pointer on the current platform (32-bit is 4, 64-bit system is 8 ),
The size of ListNode includes a pointer and an int, which must be larger than the value returned by sizeof(v).
So it is very likely that a memory access error will occur at runtime.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!