简体   繁体   中英

Error: not a member of structure or union, causing memory leaks

Im trying to make a linked list in c wich can take in a string as data and I have implemented a push, free and pop function but my problem is that in the pop function it doesnt recognize the name as a member when I try to free it.

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;
}

Im guessing it has something to do with Im using pointer to pointer wrong? Kinda stuck

You need to put parentheses around (*head) to make the statement free((*head)->name); . free(*head->name) is interpreted as free(*(head->name)) , which is why the compiler yells at you.

Citing this Stack Overflow post, the reason is because postfix operators ( -> ) have greater precedence than unary operators (*) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM