3

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

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Prototype
  • 114
  • 1
  • 9

1 Answers1

3

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 (*).

Community
  • 1
  • 1
Robert Lacher
  • 656
  • 1
  • 6
  • 16