Josee
Josee

Reputation: 180

Freeing a struct

I have a linked list struct on me, and I used a node struct to help me store data and know where each node is pointing to. In the creation of my list, I did this:

struct list {
 
 struct node *Head;
 struct node *Tail;
}

struct node{
  int val;
  struct node * next;
}
struct list create_list(){
    struct list new_list;
    new_list = malloc(sizeof(struct list));
}

Then, when I am trying to free the list that I malloced for, I did this

void free_list(struct list linked_list){

  free(linked_list);
}

However, I realize that I may have malloced wrong, because when you malloc, you need to assign it to a pointer. When I want to free the linked_list that I originally malloced for, nothing really changes.

I think this may be because the linked_list that I sent into free() is not a pointer, thus no changes have been made. I tried adding & and * to it, but I end up getting errors....

Any tips or help is appreciated.

Edit:

Fixed Typo on the struct list.

This is hw, so I cannot change the parameters of the functions, which is what is giving me a hard time freeing the linked list I made. This is because the function free_list() cannot change its parameter into a pointer linked list, so I don't know exactly what to do.

I will also take note of when I am mallocing for the linked list in the create_list function.

Upvotes: 0

Views: 105

Answers (1)

Joshua
Joshua

Reputation: 43327

Yay for passing the linked list around by value rather than on the heap for something that small.

Is this more like what you want:

struct list create_list(){
    struct list new_list = { NULL, NULL };
    return list;
}

void free_list(struct list linked_list){
    struct node *next;
    for (struct node *node = linked_list.Head; node; node = next;)
    {
        temp = node->next;
        free(node);
    }
}

Thus freeing only the list nodes that were allocated with malloc().

Upvotes: 1

Related Questions