Search code examples
clinked-listnodesfree

free function for linked-list not working


I've pasted my function code below to free to contents of the following structure:

struct LetterFrequencyPair
{
    char character;
    int frequency;
    struct LetterFrequencyPair* next; 
};

Creating and displaying the list isn't an issue and works fine. However, when I got to free function nothing happens. To try to pin point the cause of the issue I added printed step statements to my code. (Seen in the function below) to see how much of the code executes. On the output all I get is "Step 1" and nothing else so that would suggest the error is after that line. I'm not sure what is incorrect here as it's the same format I've used in another linked-list exercise.

Please let me know if you spot where I've gone wrong. Also if you need to see the whole code (I'm pretty sure you shouldn't, as this is where the error is) let me know and I'll edit the question to add it in. :)

 void freeList()
{
    struct LetterFrequencyPair* temp;
    temp = root;
    if (temp == NULL)
        {
            printf("List is empty.\n");
        }
    else
    {
        printf("step 1\n");
        while(temp != NULL);
        {
            printf("Step 2.\n");
            struct LetterFrequencyPair* nexttemp = temp->next;
            printf("step 3\n");
            free(temp);
            printf("Step 4\n");
            temp = nexttemp;
            printf("5\n");          
        }
        printf("\n");
    }
}

Solution

  • The error was spotted by @Alexander Dmitriev (He commented on the question).

    The error was the ; in the line while(temp != NULL);

    Removed the ; and the function now works fine.