释放具有结构节点的链表结构

free a struct of a linked list that have struct nodes

我有一个链表结构,里面有一个节点结构

struct gradeNode {
char courseName[sizeName];
int grade;
struct gradeNode *next;
struct gradeNode *prev;

struct gradeList {
struct gradeNode *head;
struct gradeNode *next;

我要免费销毁名单!!但我得到了访问冲突异常任何帮助

void destroyList(struct gradeList *head)
{
    struct gradeNode* tmp;

    while (head!= NULL)
    {
        tmp = head;
        head = head->next;

        free(tmp);
    }

    free(head);
}

这是主要内容

int i = 0;
for (i; i < numOfStuds; i++) {
    destroyList(&students[i].gradelist);
}
void destroyList(struct gradeList *head)
{
    struct gradeNode* tmp;

    while (head!= NULL)
    {
        tmp = head; //<<<<<<< assigning a struct gradeList* to a struct gradeNode*
        head = head->next;

        free(tmp); //<<<<<<< freeing the alias
    }

您正在将一种类型的指针分配给另一种类型的指针,然后释放它,这尤其有问题,因为 struct gradeList 似乎是 struct gradeNode 的成员。

检查你的警告。您没有收到 tmp = head 的警告吗?使用 gcc 7.2 我得到:

[x86-64 gcc 7.2 #1] warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]

https://godbolt.org/g/EWfLCn