The solution for LeetCode 369 leaks memory
Closed this issue · 3 comments
A small niggle: The C++ solution for "369. Plus One Linked List" has a memory leak. It leaks the dummy node in those cases where it is not used. Of course, LeetCode tends to leak all of the nodes it uses it its linked lists, so cleaning up this one node may be a fool's errand. Nevertheless, I would delete it when dummy->val is 0.
I cannot control what LeetCode does with a linked list once I pass it back to LeetCode. It very well may leak the whole thing. But I can control what happens in my code. If I allocate a dummy node that is later discarded, I will delete it.
class Solution {
// My implementation of the algorithm by @doocs
// https://github.com/doocs/leetcode/blob/main/solution/0300-0399/0369.Plus%20One%20Linked%20List/README_EN.md
public:
ListNode* plusOne(ListNode* head) {
ListNode* carry_node = new ListNode(0, head);
// Find the rightmost node where `val != 9`.
auto rightmost_non_9{ carry_node };
for (auto p{ head }; p; p = p->next) {
if (p->val != 9) {
rightmost_non_9 = p;
}
}
// All digits after the `rightmost_non_9` are 9. They are
// like an odometer sitting at 999,999, getting ready to
// roll over to 000,000. Adding 1 to the 9 on the far right
// (in the 1s place) will cause all the 9s to become 0, and
// feed a carry through to the `rightmost_non_9`.
++rightmost_non_9->val; // Add the carry.
for (auto p{ rightmost_non_9->next }; p; p = p->next) {
p->val = 0; // All following 9s become 0.
}
// If the `carry_node` was not used, delete it.
if (carry_node->val) {
head = carry_node;
}
else {
carry_node->next = nullptr;
delete carry_node;
}
return head;
}
};Hi @tbxfreeware , thanks for your feedback.
The C++ code on the LeetCode platform differs from the engineering implementation, and manual memory deallocation is generally not required.
Yeah, I get it. The LeetCode testing framework will accept programs that do not carefully manage the free store. That may be okay for seasoned professionals (who won't get tricked!), but it is still one of my biggest pet peeves with LeetCode.
LeetCode encourages novice programmers to leak memory! LeetCode allows them to believe they have done a good job, when, in fact, they have not. Many will not even understand that there is a problem.
Those guys and gals are developing bad habits, habits that may lead to catastrophe when and if they ever become pros.