C语言 错误:不是结构或联合的成员,导致内存泄漏



我试图在c中创建一个链表,可以将字符串作为数据,我已经实现了一个push, free和pop函数,但我的问题是,在pop函数中,当我试图释放它时,它不识别该名称为成员。

typedef struct list
{
    char* name;
    struct list* next;
} node;

void free_list(node*head)
{
    if(head==NULL){
        return;
    }
    node* temp=NULL;
    while (head!= NULL)
    {
        temp=head->next;
        free(head->name);
        free(head);
        head=temp;
    }
    head=NULL;
}
/*add elements to the front of the list*/
void push_list(node **head, char* name)
{
    node *temp=malloc(sizeof(node));
    if(temp==NULL)
    {
        fprintf(stderr,"Memory allocation failed!");
        exit(EXIT_FAILURE);
    }
    temp->name=strdup(name);
    temp->next=*head;
    *head=temp;
}

void pop_list(node ** head) {
    node * next_node = NULL;
    if (*head == NULL) {
        return;
    }
    next_node = (*head)->next;
    free(*head->name); //this line generating error
    free(*head);
    *head = next_node;
}
bool empty_list(node *head){
    return head==NULL;
}

我猜这与我使用指针指向指针错误有关?有点困

您需要在(*head)周围加上括号以使语句free((*head)->name);free(*head->name)被解释为free(*(head->name)),这就是为什么编译器会对你大喊大叫。

引用这篇Stack Overflow文章,原因是后缀操作符(->)比一元操作符(*)具有更高的优先级。

最新更新