Reputation: 1167
This is a school assignment and I have most of it under control, but there is a small part that is creating a memory leak and I have no more ideas on how to fix it.
We have created a memory allocator, and the trouble part are this two functions.
This first one cannot be modified
void destroy (){
free():
tot_alloc = 0; }
This second one is the one I'm working on
void free(){
munmap(pool, PAGE_SIZE);
Page* f = this;
f = f->prev;
if (f != NULL)
f->destroy();
}
I have written all of the free() function and was asked in the assignment to call destroy(). I realize that this function is not destroying the first "this" because immediately is going to f->prev but I have no clue how to make it first destroy this and the go to prev.
I hope this is not a too silly question.
Many thanks!
Nico
Upvotes: 0
Views: 178
Reputation: 182779
To remove an element from a singly-linked list, you must walk to that element to find the element before it in the list. Then you have to 'stitch' around it. Like this:
void free()
{ // Note: This has no error checking!
Page *f = tail, *next_f = NULL;
while(f != this)
{ // find this node to find the node after this node
next_f = f;
f = f->prev;
}
// found it. Now, next_f is the node after this node.
// close the chain so this link can go away
if (next_f == NULL) // there is no node after us, we must be the tail
tail = prev; // the tail is now whatever node is after us
else // in the node after us, the node before it is now the node before us
next_f->prev = prev;
destroy(); // we are unlinked from the chain so can now be freed
}
Upvotes: 2