Reputation: 11
I have a dynamic memory allocation of List
. How can I erase this memory when the program ends?
Outside the function I do not have access to newList
and if I erase it in function and delete the newList
before I return, then basically I return nothing.
Is newList
deleted automatically when the program terminates or do I need to manually delete it?
//reverse the list, return new list
List* reverseList(List &listToReverse) {
//dynamic memory allocation
List* newList = new List;
//pointer to first node
Node* currentPtr = listToReverse.getFirstNode();
while (currentPtr != 0) {
newList->AddElement(currentPtr->getdata());
currentPtr = currentPtr->getNextPtr();
}
Node* currentNode = newList->getFirstNode();
int size = newList->size();
while (currentNode != 0) {
currentNode->setId(size);
size--;
currentNode = currentNode->getNextPtr();
}
return newList;
}
int main() {
List l1;
cout << "The reversed list: " << endl;
reverseList(l1)->print();
system("pause");
return 0;
}
Upvotes: 0
Views: 1323
Reputation: 1130
To fix you issue, you have a couple of solution:
With modern OS, the memory will be cleaned after your program terminates BUT this is not a solution ! Always clean up every resources you have used !
* If you make a shallow copy and your type have (raw) pointers, the pointer inside the copy will point to the same object as the original. Which means that once the original delete his memory, the pointers in the copy will point to invalid memory.
Upvotes: 1