I have a code like below :
#include <iostream>
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr){}
ListNode(int x) : val(x), next(nullptr){}
ListNode(int x, ListNode *next) : val(x), next(next){}
};
void print(ListNode *head) {
ListNode *l = head;
while (l)
{
std::cout << "val is " << l->val << std::endl;
l = l->next;
}
}
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
{
int sum = 0, quo = 0, rem = 0;
ListNode *head = (ListNode *)malloc(sizeof(ListNode));
ListNode *curr, *prev = nullptr;
while (l1 || l2)
{
// Calculate value
sum = (l1->val + l2->val + quo);
quo = sum / 10;
rem = sum - quo * 10;
// Add node
if(prev == nullptr) {
curr = head;
} else {
curr = (ListNode *)malloc(sizeof(ListNode));
prev->next = curr;
}
curr->val = rem;
prev = curr;
l1 = l1->next;
l2 = l2->next;
}
return head;
}
int main() {
ListNode *node1_1 = (ListNode *)malloc(sizeof(ListNode));
ListNode *node1_2 = (ListNode *)malloc(sizeof(ListNode));
ListNode *node1_3 = (ListNode *)malloc(sizeof(ListNode));
node1_1->val = 2;
node1_2->val = 4;
node1_3->val = 3;
node1_1->next = node1_2;
node1_2->next = node1_3;
ListNode *node2_1 = (ListNode *)malloc(sizeof(ListNode));
ListNode *node2_2 = (ListNode *)malloc(sizeof(ListNode));
ListNode *node2_3 = (ListNode *)malloc(sizeof(ListNode));
node2_1->val = 5;
node2_2->val = 6;
node2_3->val = 4;
node2_1->next = node2_2;
node2_2->next = node2_3;
free(node1_1);
free(node1_2);
free(node1_3);
free(node2_1);
free(node2_2);
free(node2_3);
print(addTwoNumbers(node1_1, node2_1));
}
The problem is, when I am trying to run this code on vscode, I keep getting error :
/bin/sh: line 1: 96278 Segmentation fault: 11 "/Users/cpp/"leet_add_two_nums
I suspect that this issue is related to malloc, but cannot find a clue.
I have tried to free after malloc, but that was not the problem.
I am very new to C++, can anyone help?
Also, I would really appreciate if anyone tell me how I could improve my code!
Thanks so much in advance!
iostream, so I'm assuming this really is C++ and not C...in which case, don't use rawmallocandfree!! At least usenewanddelete, but even better would be switching to smart pointers.