当我使用 free() 时,c 中的程序遇到无限循环

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

我在 c 中尝试了一个链表程序,我在其中使用 malloc() 动态分配内存,然后当我尝试在函数末尾使用 free() 时,程序进入了无限循环。

为什么会这样?

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

您在错误的地方使用了free(),导致您的列表中删除了新插入的节点。

Should I use free() at all?

是的,因为您正在使用 malloc()。您动态分配的内存应该由您取消分配,否则会发生内存泄漏。

then where should I be using free() then?

代替您不再需要列表的代码。例如,在 main().

的末尾

无关,但是通过查看您的 insert(),我可以看出 head 是一个全局变量,应该尽可能避免。将它作为参数传递给您的列表函数,并使该变量成为非全局变量是更好的方法。如果需要,请查看此 list's 代码,该代码有完整的注释,是我过去学习的代码。


Do I cast the result of malloc?没有!