RayLeong
asked on
delete keyword
I have a link list and i wish to delete the entire list
free the memory back to the OS. Does the following codes
does what i want?
List* list = new List;
....
....
delete[] list; // list points to the head
list = NULL; // of the link list
Or should i do a loop.
List* temp = list;
while(list) {
list = list->next;
delete temp;
temp = list;
}
list = temp = NULL;
Does the first method works? What is the best way to
free the memory held by a link list? I want to be
sure that all memory is free, does the second method
actually free the entire list or i must go into the
list and free every variable one by one.
free the memory back to the OS. Does the following codes
does what i want?
List* list = new List;
....
....
delete[] list; // list points to the head
list = NULL; // of the link list
Or should i do a loop.
List* temp = list;
while(list) {
list = list->next;
delete temp;
temp = list;
}
list = temp = NULL;
Does the first method works? What is the best way to
free the memory held by a link list? I want to be
sure that all memory is free, does the second method
actually free the entire list or i must go into the
list and free every variable one by one.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Hi LucHoltkamp and basant
Thanks for the detailed explaination.
Rgds,
Raymond
Thanks for the detailed explaination.
Rgds,
Raymond
should be used with new[]. What I mean is :
int* a = new int[10];
...
delete[] a;
When you use new[] then the C++ library also stores
the number of bytes you asked. Which it uses during
deletion by delete[].
Your second way is the write way to delete. But
if you want to use the first syntax. You can
overload delete[] operator and write the same
code( second) as you mentioned.