Could someone please tell why i'm getting memory limit exceded for the below c++ code

......

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

```
int sum = 0,carry = 0;
struct ListNode * ans = NULL;
struct ListNode * prev = NULL;
struct ListNode* temp = NULL;
while(l1 || l2)
{
//ans = (ListNode*)malloc(sizeof(ListNode));
sum = l1->val + l2->val + carry;
carry = sum/10;
sum = sum % 10 ;
temp = (struct ListNode*)malloc(sizeof(struct ListNode));
temp->val = sum;
temp->next = NULL;
if(!ans)
ans = temp;
else
prev->next = temp;
prev = temp;
if(l1->next)
l1 = l1->next;
if(l2->next)
l2 = l2->next;
}
if(carry)
{
temp = (struct ListNode*)malloc(sizeof(struct ListNode));
temp->val = carry;
temp->next = NULL;
prev->next = temp;
}
return ans;
```

}

....

saw similar solutions submitted by other people which were accepted