JC94
JC94

Reputation: 159

writing a function that frees memory created from a linked list

I have the following code of a struct that defines a node of a linked list

struct list {
    struct student s;
    struct list *next;
};

My student struct is defined as the following

struct student{
    unsigned short year;
    unsigned short grade;
    unsigned char *details;
};

So assuming my program creates a linked lists of students, I want to write a function that frees every single malloc call i made.

In my program I make a malloc call every time I intialize *details, and every time i create a node for the list.

If this helps, this is my function that creates a node:

struct list *create_node(struct student *p) {
    struct list *node = malloc(sizeof(struct list));
    node->p = *p;
    node->next = NULL;
    return node;
}

I want to write a function that fress all the memory that was made with malloc to hold the list.

Here is my attempt

void free_list(struct list *node){

    // free this first node
    free(node->p.details);
    while (node->next != NULL){
        // become the next node and free
        node = node->next;
        free(node->p.details);
    }

Upvotes: 0

Views: 180

Answers (1)

mahendiran.b
mahendiran.b

Reputation: 1323

your free function can be like this

void free_list(struct list *node){

struct list  *temp = NULL;

// free this first node
//free(node->p.details);
while (node != NULL){
    temp = node;
    // become the next node and free
    node = node->next;
    free(temp->p.details);
    temp->p.details = NULL;
free(temp);
}

Upvotes: 2

Related Questions