c - 此 "good taste"和 "bad taste"代码中是否缺少 free()?

标签 c linked-list

在一次关于 Linus Torvalds 的采访中,他分享了拥有“良好品味”的重要性。他用以下代码解释了 good taste。

带有“坏品味”的代码

remove_list_entry(entry)
{
    prev = NULL;
    walk = head;

    // Walk the list

    while (walk != entry) {
        prev = walk;
        walk = walk->next;
    }

    // Remove the entry by updating the head
    // or the previous entry

    if (!entry)
        head = entry->next;
    else
        prev-next = entry->next;
}

具有“品味”的代码

remove_list_entry(entry)
{
    // The "indirect" pointer points to the
    // *address* of the thing we'll update

    indirect = &head;

    // Walk the list, looking for the thing that
    // points to the thing we want to remove

    while ((*indirect) != entry)
        indirect = &(*indirect)->next;

    // .. and just remove it
    *indirect = entry->next;
}

这两个例子都没有使用free()来释放要删除节点的内存。谁能告诉我为什么代码是这样写的?还是我对 C 或链表的概念有误?

最佳答案

注意此函数的语义也很重要。它旨在从列表中删除一个节点,而不是像您在问题中建议的那样删除该节点。至少函数名称暗示了这一点。如果它在不宣传该语义的情况下删除节点,我会感到惊讶。

此外,我们无法单独知道对象是如何分配的,因此该函数不能合理地假设它是一个堆对象并且 free() 它 - 这会导致运行时错误如果对象是静态的。

调用者可能正在从列表中删除对象并继续使用它,此函数的责任是维护列表,而不是列表中独立存在的对象。 entry 的所有者有责任管理其内存。

关于c - 此 "good taste"和 "bad taste"代码中是否缺少 free()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56253372/

相关文章:

c - 如何根据数组在不同行中的升序和降序打印c中的数组?

c - C 中的堆栈溢出漏洞利用

c++ - Fortran 77 转换为 C++

c - 删除链表中的节点

c++ - 链表构造中,开头加一个变量的代码是什么?

python - 将项目添加到链接列表的末尾会产生奇怪的结果

c - 从动态分配的二维数组中获取值

java - 缓冲区溢出 (vs) 缓冲区溢出 (vs) 堆栈溢出

c++ - "no match for ' operator= '"in c++, 试图建立链表

c - 为什么我的指针被锁定在一个范围内?