Deleting linked list from the beginnig

Hello,
I am trying the delete all the elements in a linked list in the beginning.
I used the following code, it seems like that it complied fine with ./a.out,
however, when I use valgrind ./a.out, it says there are memory errors.
Could you help me to fix the problem please?
Thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  void List::emptyTheList()
{
    cout << "inside function emptyTheList() ";
    cout <<"starting to traverse list to delete nodes"<<endl;

    if (head==NULL)
    {
    	cout<<"there is no elements in the list" <<endl;

    }

    else
    {
	DR *temp1;//DR is a class
	temp1=head->getNext();
	while(temp1!=NULL)
	{
		free(head);
		head=temp1;
		temp1=head->getNext();
	}

    }
   

} //END function emptyTheList() 
1
2
3
4
temp1=head->getNext();
while(temp1!=NULL)
{
   ...


Here, in the case where temp1 == NULL, the freeing of head will be skipped. You could restructure this loop so it's a do-while instead.
Topic archived. No new replies allowed.