Reputation: 13
I'm confused as to when I should be deallocating the following object from memory:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode* addTwoNums(ListNode* l1, ListNode* l2){
ListNode *head = new ListNode(0);
...
return head->next;
}
Since I'm returning the head object, when should I delete it such that I don't have a memory leak?
Upvotes: 0
Views: 69
Reputation: 1551
Every function accepting or returning a pointer needs to have a contract regarding who is responsible for owning the resource pointed to by the pointer. When you use raw pointers, such as you did, this contract is implicit, which means you'll need to figure out who frees the object (it seems obvious that the caller must).
If you read up on std::unique_ptr
and std::shared_ptr
, you'll find some very nice and useful alternate ways of expressing this contract, which will help you sidestep the question of who owns the object, and rely on the standard library to determine that.
Upvotes: 2