我有一个链表的结构,里面有一个节点结构
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);
}
答案 0 :(得分:1)
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]警告:从不兼容的指针类型初始化[-Wincompatible-pointer-types]