c - 如何释放邻接链表分配的内存?

标签 c memory-management free dynamic-memory-allocation

我想释放邻接链表内存 这是我的数据结构和两个可以为图形分配内存的函数。 如何释放分配的内存? 感谢您的帮助

struct ListPoint {
    int dest;
    int weight;
    struct ListPoint* next;
};
struct List {
    struct ListPoint* head;
};
struct Graf {
    int V;
    struct List* array;
};
struct ListPoint* newAdjencyListPoint(int dest, int weight)
{
    struct ListPoint* newPoint =
        (struct ListPoint*)malloc(sizeof(struct ListPoint));
    newPoint->dest = dest;
    newPoint->weight = weight; 
    newPoint->next = NULL;
    return newPoint;
}
struct Graf* createGraph(int V)
{
    struct Graf* graf = (struct Graf*)malloc(sizeof(struct Graf));
    graf->V = V;
    graf->array= (struct List*)malloc(V * sizeof(struct List));
    int i;
    for (i = 0; i < V; ++i)
        graf->array[i].head = NULL;
    return graf;
}

最佳答案

以下代码可能就是您正在寻找的代码:

freeLinkedList(struct List list){
   struct ListPoint *aux,*it = list.head;
   while(it != NULL){ //free a node and go to the next one
      aux = it->next;
      free(it);
      it = aux;
   }
}
freeAdjList(struct Graf* adj_list){
   for(int i=0;i<adj_list->V;i++) //free each linked list
      freeLinkedList(adj_list->array[i]);
   free(adj_list->array); //free the linked list array
   free(adj_list); //free the adj matrix itself
}

关于c - 如何释放邻接链表分配的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43824178/

相关文章:

c - 无法访问代码并且无法读取所有输入字母

c - 如何使用指针对结构数组进行排序?

c++ - 使用 itoa() 的最佳实践是什么

c++ - 我可以使用 C++ 中的内置类型安全地新建 [],然后转换指针,然后删除 [] 吗?

c++ - 如果 malloc() 在同一位置分配内存,则访问已释放的指针可能会导致数据损坏,除非已释放的指针设置为 NULL

C语言 : Releasing memory of pointers to struct

c - 在 C 中操作字符串数组

C 标准 I/O 与 UNIX I/O 基础

c - 需要帮助为数组的结构数组分配内存

c - 使用 free() 时为 "Heap corruption detected"