![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Mar 2005
Posts: 8
Rep Power: 0
![]() |
memory leak question
I'm building a linked list class and have a question about one of my memeber functions. This is what i have now:
//Removes the last item from a linked list
void linked_list::pop_tail()
{
ll_item *cursor;
cursor = head;
while (true)
{
if(cursor->next_item->next_item == NULL)
{
delete cursor->next_item;
cursor->next_item = NULL;
break;
}
cursor = cursor->next_item;
}
size--;
}It works fine but I'm curious about the necessity of the first statement inside the if clause. Do I really need to delete the memory contents of next_item if I'm setting it to null, i.e. can I get away with just setting it to null without a memory leak? |
|
|
|
|
|
#2 |
|
Professional Programmer
|
if you free next_item you'll have to reallocate next time you want to use it, so you can just leave it NULL, it should be allocated already, so you should be fine.
Dizz |
|
|
|
|
|
#3 |
|
Professional Programmer
Join Date: Mar 2005
Location: Glasgow, Scotland
Posts: 314
Rep Power: 4
![]() |
Ew, no! next_item is a pointer. Setting it to NULL will leave the memory allocated, sure, but you'll have no record of the address, meaning the structure exists but your program has no way of getting back at it. If you try to indirect through a null pointer, you'll get a Segmentation Fault (on Unix; some equivalent, probably more serious, and more vague error on Windows toys).
In other words, if you were to omit delete, you'd still need to allocate again next time with new, but you'd leak memory each time this happened. If you want to keep a pool of memory on the heap so you don't have to keep allocating and deallocating, you have to work harder than this and keep a list of references to your available allocated memory that you can look up - effectively implement your own mini memory manager on top of the existing one. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|