Umashankar Varma
Umashankar Varma

Reputation: 31

memory leak in CreateList function (linked list)

I tried checking for memory leak using valgrind with below options:

valgrind --leak-check=full -v ./linkedlist2

Valgrind says there is a memory leak in createList() function, but I am not able to find the reason for it. Could you please help me to understand what is the reason for the memory leak?

Relevant code:

struct node{
    int data;
    struct node* next;
};

struct node* createList(int num)
{
    struct node* temp = NULL;
    struct node* head = NULL;
    struct node* curr = NULL;

    int i = 0;
    if(num <= 0)
    {
        printf("Invalid size for createList\n");
        return;
    }

    for(i=0;i<num;i++)
    {
        temp = malloc(sizeof(struct node)); //allocate memory
        temp->data = i+1;
        temp->next = NULL;

        if(i == 0)
        {
            head = temp;
            curr = temp;
        }else   {
            curr->next = temp;
            curr = temp;
        }
    }
    curr = temp = NULL;
    //curr->next = temp->next = NULL;
    free(curr);free(temp);
    return head;
}

enter image description here

Upvotes: 2

Views: 154

Answers (2)

roottraveller
roottraveller

Reputation: 8232

This line causes the problem

curr = temp = NULL;
//curr->next = temp->next = NULL;
free(curr);free(temp);

Well here you are assigning NULL to struct node pointer curr and temp, henceforth the memory pointed by it goes garbage. you first free the memory using free() and the assign it to NULL

Replace your above code with this

free(curr);
free(temp);
curr = temp = NULL;

Upvotes: 1

Tomislav Kostic
Tomislav Kostic

Reputation: 68

First thing you should know is that for every allocation of memory(malloc()) you need to free that memory(free()),and that is exactly what valgrind returned as answerenter image description here

this lines of code would fix that

while(head!=NULL){
    temp=head;
    head=head->next;
    free(temp);
   }

But function createList() is supposed to create list not to delete it, so except for mental gymnastic I do not see purpose of creating list than immediately deleting. I recommend that you make new function removeList() that free memory which you call at the end of main function.

Upvotes: 0

Related Questions