Search code examples
clistpointersmallocfree

Freeing struct elements of a linked list


I am trying to free the struct elements of a struct list with a function. This is the problem:

error: no member named 'next' in 'struct _list' alist = alist->next;

typedef struct _element element; 


typedef struct _list { /* Separater Wurzelknoten */
    element *first;    /* Anfang/Kopf der Liste */
    int count;         /* Anzahl der Elemente */
} list;

struct _element {
    char title[MAX_STR];
    char author[MAX_STR];
    int year;
    long long isbn;
    element *next;
};

My function:

void free_list(list *alist) {
    /* HIER implementieren. */
    list *tempPointer;
    while(alist != NULL) {
        tempPointer = alist;
        alist = alist->next;
        free(tempPointer);
    }
}

I cant't change the parameters (list *alist). So how do I get access to next?


Solution

  • The error is there because list doesn't have a next pointer, it only contains a pointer to the list. Since element has the next pointer you should replace the temporary variable's type with element and use that instead:

    void free_list(list *alist) {
      element* cur = alist->first;
      while (cur != NULL) {
          element* tempPointer = cur;
          cur = cur->next;
          free(tempPointer);
      }
      // if alist was allocated with malloc()
      free(alist);
    }