Search code examples
clinked-listdynamic-memory-allocationfree

Free() after using malloc in linked list


I know that each time i use malloc or calloc i have also to free that memory, but in this specific case i can't understand when free the memory and how, if i free inside the generate() function the code doesn't work anymore.

void generate(int n){
     node *tmp,*new;
     int num,i;
     head = malloc(sizeof(node));
     if (head==NULL){
         perror("malloc");
         EXIT_FAILURE;
     }
     num = rand() % (42 - (-42) + 1) - 42;
     head->data = num;
     head->next = NULL;
     tmp = head;

     for(i=1;i<n;i++){
         new = malloc(sizeof(node));
         if(new == NULL){
            perror("malloc");
            EXIT_FAILURE;
         }
         num = rand() % (42 - (-42) + 1) - 42;
         new->data = num;
         new->next = NULL;
         tmp->next = new;
         tmp = tmp->next;
     }
}

int main(){
    int n;
    do {
        printf("give me the size of the linked list (less than 42):");
        scanf("%d",&n);
        if(n>42){
          printf("i said less than 42. \n Please ");
        }
     } while(n>41);

     srand(time(NULL));
     generate(n);
     printlist();
     return 0;
}

Solution

  • Use separate function for linked list deletion as follows:

    void deleteList()
    {
        node *tmp = head;
        while(tmp != NULL)
        {
            tmp = tmp -> next;
            free(head);
            head = tmp;
        }
        head = tmp;
    }
    

    use above function to free memory allocated for linked list

    generate(n);
    printlist();
    
    // FREE MEMORY
    // function call
    deleteList();
    return 0;