力扣报错:runtime error: member access within address 0x602000000000 with insufficient space for an object of type ‘ListNode’ (solution.cpp)
上述意思是内存读取错误
ListNode* point1 = l1;
ListNode* point2 = l2;
ListNode* head ;
ListNode* point3 = head ;
int n1 = point1?point1->val:0;
int n2 = point2?point2->val:0;
int add = 0;
point3->val = n1 + n2 + add;
其报错语句如下:
Line 22: Char 17: runtime error: member access within address 0x602000000000 with insufficient space for an object of type 'ListNode' (solution.cpp)
0x602000000000: note: pointer points here
显示内存读取错误;通过查询资料终于发现错误原因在于ListNode* head建立了一个链表指针,但一直未初始化该链表指针,导致系统一直不知道该链表指针指向着哪块内存。因此在执行 point3->val = n1 + n2 + add;时,我最开始认为这句话是类似于初始化该链表指针指向的内存空间,但仔细思考才知道这句话的意思是先通过point3指针找到该指针指向的内存空间,然后在该内存空间的val值处进行赋值操作,这一步骤并没有给point3指针指明其内存指向,因此会出现内存读取异常的错误。
其实在很多情况下,特别是做关于链表的题目,在创建指针完之后,并没有指明该指针指向的内存空间在哪(或者说系统没有分配该指针的内存空间),最终导致在赋值的时候,会产生内存读取的错误。
解决方法:
这一问题的解决方法就是提前人工分配给该指针指向的空间一块内存。
ListNode* point1 = l1;
ListNode* point2 = l2;
ListNode* head = new(ListNode) ;//修改在这一句即可
ListNode* point3 = head ;
int n1 = point1?point1->val:0;
int n2 = point2?point2->val:0;
int add = 0;
point3->val = n1 + n2 + add;