Infinite loop while clearing a linked list

Hi all, I am having an issue with an infinite loop when trying to clear my code. I have been staring at it for over an hour but without any luck. I tried a for loop but switched to a while loop to see if I was missing anything obvious. I have included both the for and while loops.
Currently when it is running, it runs continuasly on this function. I am using a G++ compiler on a unix server. Is there a way to step through code?

Thank you for your time!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Post Condition: The list still exists, but is empty.
template <class T>
void LinkedSortedList<T>::clear()
{
        LinkedNode<T> *temp;
        /*for (LinkedNode<T> *thisNode = HeadPtr; thisNode != NULL; thisNode = temp)
        {
                temp = thisNode->next;
                delete thisNode;
        }
        */
        LinkedNode<T> *thisNode;
        thisNode = HeadPtr;
        while (thisNode != NULL)
        {
                temp = thisNode->next;
                delete thisNode;
                thisNode = temp;
        }
        numberOfNodes = 0;
}


I get that thisNode is deleted and so maybe I can't assign it something? Any other ideas as to how to do this?
Last edited on
A bit unsure about the G++, compiler although your code does look almost correct. Are you specifically setting the last node to NULL or a 0? Your compiler might be interpreting it differently, hence the infinite loop. For general debugging you might want to set up Eclipse with CDT if you want to step through. Try this and let me know how it goes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template <class T>
void LinkedSortedList<T>::clear()
{
        LinkedNode<T> *temp;
        /*for (LinkedNode<T> *thisNode = HeadPtr; thisNode != NULL; thisNode = temp)
        {
                temp = thisNode->next;
                delete thisNode;
        }
        */
        LinkedNode<T> *thisNode;
        thisNode = HeadPtr;
        while (thisNode)
        {
                temp = thisNode->next;
                delete thisNode;
                thisNode = temp;
        }
        numberOfNodes = 0;
        HeadPtr = 0;       //to indicate a deleted list
}
Last edited on
Thanks! What I ended up doing was replacing "thisNode" with the HeadPtr. I am wondering if it has something to do with HeadPtr being declared globally while in contrast, thisNode is declared locally? Doesn't make a lot of sense to me, but it's my best guess.
Now all my code is working! Yay! But... I am getting a segmentation fault at the end. Oh well, one last thing to debug. :)

Thanks again!
Technically your solution of replacing thisNode with HeadPtr works but not elegant enough. Anyway, as you say you're getting a segmentation fault at the end, did you forget to set the HeadPtr to null(0)? You could have left it dangling.
Last edited on
Topic archived. No new replies allowed.