我们如何释放节点携带指针到某个位置的内存

时间:2011-12-15 05:58:38

标签: c linked-list

我有链接列表,其节点结构在下面给出

  struct node
  {
  char *p;
  struct node *next;
  }*start;

现在我们char * p是指向malloc调用分配的内存位置的指针。同样,整个也是使用malloc分配的。现在想释放malloc调用占用的空间,如下所示

  main()
 {
   struct node *tmp;
   tmp=malloc(sizeof(struct node));
   tmp->next=NULL;
   tmp->p=malloc(2*sizeof(int));

   free(tmp->p);
   free(tmp);

 }

这是免费记忆的正确方法吗?这里需要什么?

2 个答案:

答案 0 :(得分:2)

这是正确的方法但不要忘记在使用free之后将指针指向NULL,否则指针将成为悬空指针。

像这样使用它们 -

自由(TMP-指p); tmp-> p = NULL;

答案 1 :(得分:0)

你正确地释放了,虽然通常你会有一个指向第一个节点的指针,然后按照指针循环遍历列表。 e.g。

struct node *first;
... list created, first pointing to first in list, where last next is == NULL ...

while (first != NULL) 
{
  struct node* next = first->next;
  free( first->p );
  free( first );
  first = next;
}

btw为什么你将p声明为char*但是分配整数?错字?