Brandon
Brandon

Reputation: 401

Am I freeing this linked list in the correct manner?

Is this the correct way to free a linked list? I have the following structs:

struct Courses{
    char *courseName;
    int creditValue;
    Courses *next;
}Courses;

struct Student{
    char *name;
    int age;
    Courses *list;  //First course (node)
}Student;

This is my free function:

void freeStudent(Student *student){
    struct Courses *tmp = student->list;

    while(tmp != NULL){
        free(tmp->name);
        free(tmp);
        tmp = tmp->next;
    }
}

Am I ordering my free function wrong? Should I be doing tmp = tmp->next before freeing tmp?

Upvotes: 2

Views: 31

Answers (1)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22254

Yes it is wrong

free(tmp);
tmp = tmp->next;

After you free tmp it becomes a dangling pointer (which is why some people would set it to NULL). You shouldn't attempt to access it like this tmp->next

I would recommend this version for freeing

void freeStudent(Student *student){
    struct Courses *tmp = student->list, *pre;

    while(tmp != NULL){
        free(tmp->name);
        pre = tmp->next;
        free(tmp);
        tmp = pre;
    }
}

Upvotes: 2

Related Questions