Home > Back-end >  How to free data malloc()'d inside a loop?
How to free data malloc()'d inside a loop?

Time:02-13

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node *next;
} Node;

void reverse_print_list(Node *head)
{
    if(head == NULL)
        return;

    print_list(head->next);
    printf("%d ", head->data);
}

int main()
{
    Node *head = malloc(sizeof(Node));
    head->data = rand() % 100;
    head->next = NULL;

    Node *temp = head;
    for (int i = 0; i < 9; i  ) {
        Node* new_node = malloc(sizeof(Node));
        new_node->data = rand() % 100;
        new_node->next = NULL;

        temp->next = new_node;
        temp = temp->next;
    }

    temp = head;
    printf("Original list : \n");
    while (temp != NULL) {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n---------------------------\n");

    reverse_print_list(head);

    free(head);
    free(temp);

    return 0;
}

In the above code, inside the for loop in main(), I am dynamically allocating memory for new nodes of a linked-list and attaching every newly created node to the last node in the list. But this seems like it would result in a memory leak since I am not freeing those nodes at the end of the loop as I need those nodes to exist outside of the loop. How can I free the nodes I have created inside the for loop? Running another loop starting from head to save all the nodes' addresses and then running another loop to manually free() all of those addresses seems tedious. Is there any other way? Thanks.

CodePudding user response:

Just delete the head node and replace head with its successor. Repeat until head becomes empty. Please note, you must backup the next pointer before calling free().

int main()
{
    Node *head = malloc(sizeof(Node));
    head->data = rand() % 100;
    head->next = NULL;

    ... build and print your list ...

    while (head)
    {
       Node * remainingChain = head->next;
       free(head);
       head = remainingChain;
    }
    return 0;
}
  • Related