Search code examples
cmallocfree

program in c runs into infinite loop when I use free()


I was trying out a linked list program in c where I use malloc() to allocate memory dynamically and then when I tried using free() at the end of the function, the program runs into an infinite loop.

Why is this happening ?

void Insert(int x, int pos)
{
    struct Node *newnode = (struct Node*) malloc(sizeof(struct Node));
    newnode->data = x;
    newnode->next = NULL;
    struct Node* temp, *left, *right;
    int i = 1;
    temp = head;

    if(head == NULL)
    {
        head = newnode;
    }
    else{
        while(i != pos - 1)
        {
            temp = temp->next;
            i++;
        }
        newnode->next = temp->next;
        temp->next = newnode;
    }
    free(newnode);
}

Solution

  • You use free() in the wrong place, resulting in deleting the newly inserted node in your list.

    Should I use free() at all?

    Yes, since you are using malloc(). The memory you allocated dynamically should be de-allocated by you, otherwise memory leaks shall happen.

    then where should I be using free() then?

    In the place of your code that you do not need your list anymore. For example, at the end of your main().


    Unrelated, but by looking at your insert(), I can see that head is a global variable, which should be avoided, when able. Passing it as a parameter to your list functions, and making this variable non global is a better approach. If you want, take a look in this list's code, which is fully commented and was the one I used to learn.


    Do I cast the result of malloc? No!