基本上,我正在尝试编写一个函数,该函数以两个长度相同的链表为参数,并返回每个链表的数字之和,使每个节点根据其数字乘以10的幂,然后添加到其他节点。然而,当在vscode中运行代码时,我似乎在第15行遇到分段错误:l1sum += temp1->val * i;
而当在在线gdb编译器上运行代码时,给出的结果是正确的,没有显示任何错误,我知道为什么会发生这种情况吗?
这是整个代码:
#include <stdlib.h>
#include <stdio.h>
struct ListNode {
int val;
struct ListNode *next;
};
void addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int l1sum = 0, l2sum = 0, i=1;
struct ListNode * temp1 = l1;
struct ListNode * temp2 = l2;
while(temp1 != NULL && temp2 != NULL)
{
l1sum += temp1->val * i;
l2sum += temp2->val * i;
i = i*10;
temp1 = temp1->next;
temp2 = temp2->next;
}
free(temp1);
free(temp2);
printf("l1sum: %dn", l1sum);
printf("l2sum: %dn", l2sum);
}
int main()
{
struct ListNode * head1 = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode * head2 = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode * second1 = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode * second2 = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode * third1 = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode * third2 = (struct ListNode *)malloc(sizeof(struct ListNode));
head1->val = 2;
second1->val = 4;
third1->val = 3;
head1->next = second1;
second1->next = third1;
head2->val = 5;
second2->val = 6;
third2->val = 4;
head2->next = second2;
second2->next = third2;
addTwoNumbers(head1, head2);
}
每个人基本上都在评论的是,当建立链接列表时;下一个";指针,则在最终列表条目中放入该变量的值为"0";NULL";。如果忽略了这一点,那么基本上就是猜测该变量是否会包含NULL值,或者有一些垃圾值会指向它不应该指向的内存区域。有时可能会很幸运,程序运行时这些值会为NULL,但这是一场赌博。这样,这里是代码的一个子集,其中包含用NULL指针终止链表的附加代码。
head1->val = 2;
second1->val = 4;
third1->val = 3;
head1->next = second1;
second1->next = third1;
third1->next = NULL; /* Added to ensure the end of the list is known */
head2->val = 5;
second2->val = 6;
third2->val = 4;
head2->next = second2;
second2->next = third2;
third2->next = NULL; /* Added to ensure the end of the list is known */
在vscode之外和vscode内部都尝试一下。