【问题标题】:How to clear memory in c如何在c中清除内存
【发布时间】:2012-01-27 23:17:08
【问题描述】:

我有一个结构如下:

struct Node{
int *arr;
int *sol;
struct Node *Next;
};

我正在以这种方式创建节点:

Node* MyNode = (Node *)malloc(sizeof (struct Node));
MyNode->arr = malloc(sizeof(int)*N);
MyNode->sol=  malloc(sizeof(int)*N);

然后我将 MyNode 添加到链接列表中。如何为列表中的元素释放内存。
这是正确的:

pop(){
   free(first->arr);
   free(first->sol);
   first=first->Next; 
}

【问题讨论】:

  • 哪种语言?另外:您的结构定义中缺少;两种语言)。
  • Next 是什么?您的 Node 不包含 Next 指针。
  • 在 C 中不要强制转换 malloc 的返回值。在 C 中,类型 Node(用于指针 MyNode)不存在。在 C 中,使用 C 编译器编译 C 代码 :)

标签: c++ c memory linked-list free


【解决方案1】:

要使任何struct 成为linked-list 中的一个节点,您需要一个self-referential structure variable,它应该被声明为struct Node *next;

struct Node{
    int *arr;
    int *sol;
    struct Node *next;
}

要为链表的节点分配内存,您需要以下内容:

/* allocate memory for a node */
struct Node * MyNode = (struct Node *)malloc((int)sizeof(struct Node));
if (MyNode == NULL) {
    printf("ERROR: unable to allocate memory \n");
    return 1;
}

/* allocate memory for the content of a node */
MyNode->arr = (int *) malloc((int)sizeof(int) * N);
if (MyNode->arr == NULL) {
    printf("ERROR: unable to allocate memory \n");
    return 1;
}

MyNode->sol = (int *) malloc((int)sizeof(int) * N);
if (MyNode->sol == NULL) {
    printf("ERROR: unable to allocate memory \n");
    return 1;
}

/* add the new node to a list by updating the next variable */
MyNode->next = ... 

如果您不确定删除链表中的节点需要执行的操作,您可以使用temp 变量以更简单的方式执行相同操作。

pop()
{
    struct Node * temp = first;
    first = first->next;
    free(temp->arr);
    free(temp->sol);
    free(temp);
}

free 的拇指规则 - 对于每个 malloc(),都应该有一个 free()

OTOH,要了解删除链表中节点的各种场景,请参考this链接。

【讨论】:

    【解决方案2】:

    几乎,你需要释放节点本身:

    pop(){
       Node* old_first = first;
       free(first->arr);
       free(first->sol);
       first=first->Next;
       free(old_first); 
    }
    

    【讨论】:

    • nitpick old_first 未声明,您的回答中有编译错误:)
    【解决方案3】:
    pop(){
       free(first->arr);
       free(first->sol);
       Node* temp = first; //<========
       first=first->Next;
       free (temp);  //<=======
    }
    

    【讨论】:

    • @Mat,Roee,给我 20 秒好吗?!
    【解决方案4】:

    接近但不正确 - 您应该拥有与 mallocs 一样多的 frees。您忘记释放 Node 本身。

    要修复它,请添加一个临时的:

    Node *next = first->next;
    free(first->arr);
    free(first->sol);
    free(first); 
    first = next;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多