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

3

我正试图在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;
}

我猜测这可能与我的指针使用不当有关?有点困难。


你能把你的 main 函数也包含进来吗? - Robert Lacher
2
你是不是想说 free((*head)->name); - aschepler
是的,我指的就是那一行 :) - Prototype
1个回答

3
您需要在(*head)周围添加括号,以使语句free((*head)->name);正确。free(*head->name)被解释为free(*(head->name)),这就是编译器报错的原因。
引用此Stack Overflow帖子,原因是后缀运算符(->)优先级高于一元运算符(*)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接