deallocation of memory created by new

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
node * temp=new node; // node is a structure { int value;struct node *next; };
if(head==NULL)
{
     temp->value=val; // importing val
     temp->next=NULL;
     list->head=temp;
}
else
{
     temp->value=val;
     temp->next=head;
     list->head=temp;
}
list->length++;
display(list)


this is my create function for linkedlist..
valgrind says there is some definite memory lost at new command..
how and where do i deallocate it ??
and below is my display function.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
node *temp=list->head; 
if(temp==NULL)
{
     cout<<" \n";
}
else
{
     cout<<" "<<temp->value;
     while(temp->next!=NULL)
     {
         cout<<"->"<<temp->next->value;
         temp=temp->next;
     }
     cout<<"\n";
}


Last edited on
It's hard to tell what's going on here without the complete code.

For each invocation of new there should be a matching call to delete to reclaim that memory.

When that list is done being used, the resources it owns need to be reclaimed by calling delete on each node. The place this should be done is in the list's destructor.

Please post the rest of your code if you need more help.
Memory leaks in a linked list almost always happen during deletion of a node. BEFORE you change the pointer that points to a node, you have to call delete on that node. Otherwise that node is going to just hang out in memory but no way to access it.
Topic archived. No new replies allowed.