I came across a piece of code that use new
to allocate dynamic memory in a function, then calls this function in the main function. I suspect there are some memory leak issue, but I do not know exactly how to fix it. The following code is simplified to demonstrate the problem:
#include <iostream>
#include <vector>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* createList(void);
int main(){
ListNode* my_list = createList();
//... some code
// how to delete those objects created by new?
return 0;
}
ListNode* createList(void) {
ListNode preHead(0), *p = &preHead;
vector<int> sum = {1, 2, 3, 4, 5};
for (decltype(sum.size()) i = 0; i != sum.size(); i++){
p->next = new ListNode(sum[i]);
p = p->next;
}
return preHead.next;
}
If I understand it correctly, The function createList()
creates a list which has 6 ListNode objects.
Except the first object in the list (which is preHead
), the other 5 objects are all dynamically
allocated using new
. Finally, function createList()
returns a pointer to the second object in the list,
which is a pointer to dynamic memory.
My question is:
Is
my_list
a normal pointer or pointer to dynamic memory? How do we decide the type ofmy_list
.for example, if I write the following codeListNode l1(2);ListNode* my_list = &l1;
Then my_list
will be a normal pointer to ListNode object. What is the difference between the 2 situations?
The last 5 objects in the list are created using
new
, how to delete them inmain()
after using the list? Do I have to traverse the list and start deleting from the end of the list until all objects created dynamically are deleted?If that is the case, I think it will be cumbersome and inconvenient. How to improve
createList()
under the condition that it still returns a pointer to ListNode object.