【问题标题】:When to use free in linked list delete node code?什么时候在链表删除节点代码中使用free?
【发布时间】:2018-09-04 01:59:21
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

struct item {
    int key;
    int data;
    struct item *next;
};

struct item *head = NULL;


void delete(int key)
{
    if(head == NULL) {
        ;
    } else if(head->key == key) {
        head = head->next;
    } else {
        struct item *curr = head;
        struct item *prev = NULL;
        int found = 0;
        while(curr != NULL) {
            if(curr->key == key) {
                found = 1;
                break;
            } else if(curr->key > key) {
                break;
            }
            prev = curr;
            curr = curr->next;
        }
        if(found) {
            prev->next = curr->next;
        }
    }

}

键已排序。 delete 接受一个键,然后将其删除。它有效,但我不明白什么时候可以免费使用。

我们必须释放()我们从列表中取消链接的结构项目

【问题讨论】:

    标签: c


    【解决方案1】:

    你必须认为“malloc”和“free”与从某人那里借东西是一样的。每当您向某人 (malloc) 借一支笔时,您需要稍后归还(免费)。

    在你的情况下,你必须在确定没有任何东西可以访问它之后释放你的节点:

    #include <stdio.h>
    #include <stdlib.h>
    
    struct item {
        int key;
        int data;
        struct item *next;
    };
    
    struct item *head = NULL;
    
    
    void delete(int key)
    {
        if(head == NULL) {
            ;
        } else if(head->key == key) {
            head = head->next;
        } else {
            struct item *curr = head;
            struct item *prev = NULL;
            int found = 0;
            while(curr != NULL) {
                if(curr->key == key) {
                    found = 1;
                    break;
                } else if(curr->key > key) {
                    break;
                }
                prev = curr;
                curr = curr->next;
            }
            if(found) {
                prev->next = curr->next;
                free(curr); // Here
            }
        }
    }
    

    它的作用与借用机制完全相同:您不能在归还它(免费使用)后使用任何东西 - 否则它会崩溃。

    【讨论】:

    • 是的,但他在何时免费使用时寻求帮助。代码优化、改进和可读性是随着实践而来的,在没有正确理解的情况下强行编写新代码对他毫无帮助。
    【解决方案2】:

    在更新指向下一项的指针后,你必须删除当前的。由于当前项目将不再使用。为避免内存泄漏,您需要将其删除。

       if(found) 
       {
                prev->next = curr->next;
                free(curr)
       }
    

    【讨论】:

      【解决方案3】:

      当您不再访问该内存时,您应该将free() 内存分配给一个指针。但是你必须确保你实际上不需要它。例如,在您的代码中:

          if(found) {
              free(curr); // Here
              prev->next = curr->next;
          }
      

      这似乎可行,因为您已经找到要删除的节点,但实际上,您仍然需要访问curr 指向的数据,以便更新prev-&gt;next 的值。所以你应该在这里释放它:

          if(found) {
              prev->next = curr->next;
              free(curr); // Here
          }
      

      因为到那时,您确实不再需要访问curr 的内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-15
        • 2019-12-07
        • 1970-01-01
        • 2013-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多