0
votes

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);
    }
1
Are you having a problem with the code you've written? If so you might describe the issue you're having.mah
How do you create your student objects and are you freeing the memory that they themselves use?andypea
There is a typo. In node->p, there is no member called p.Jeyaram
There is not a p in your struct list. Maybe it is node->s = *p;γηράσκω δ' αεί πολλά διδασκόμε

1 Answers

2
votes

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