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