这是我的密码:

int pop (struct_of_ints *head_node){
int val;
if (head_node == NULL){
    fprintf(stderr, "Empty stack.\n");
    return -1;
}
else {
    struct_of_ints *curr;
    struct_of_ints *prev;
    curr = head_node;
    prev = NULL;

        while (curr->next != NULL) {
            prev = curr;
            curr = curr->next;
        }

        val = curr->value;

        if (prev == NULL)
            head_node = NULL;
    else
            prev->next = curr->next;
        free(curr)
        return val;


}

}

但是,当我尝试释放(curr)时,我得到了一个分段错误,当我运行valgrind时,我得到了诸如“Invalid free()/delete/delete[]”、“地址0x51c1f60在大小为32 free'd的块中是16字节”和“无效读取大小为8”……我不知道出了什么问题。如果有人能帮忙,我将不胜感激。谢谢!

最佳答案

您正在传递函数中的指针*head_节点,该节点按值传递。若要更新*head_节点,请尝试传递**head_节点,并将代码更改为:

int pop (struct_of_ints **head_node)
{
    int val;
    if (*head_node == NULL)
    {
        fprintf(stderr, "Empty stack.\n");
        return -1;
    }
    else
    {
        struct_of_ints *curr;
        struct_of_ints *prev;
        curr = *head_node;
        prev = NULL;
        while (curr->next != NULL)
        {
            prev = curr;
            curr = curr->next;
        }

        val = curr->value;

        if (prev == NULL)
            *head_node = NULL;
        else
            prev->next = curr->next;
        free(curr)
        return val;
    }
}

关于c - 无法在Pop函数中释放/重新分配空间?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16160180/

10-11 17:47