在优先级队列的c实现中释放struct指针数组

时间:2017-11-15 03:57:38

标签: c arrays pointers heap free

我有一个问题是释放我正在实现的优先级队列的struct指针数组。我从客户端c程序创建两个具有固定大小的动态节点指针数组。数组 heapMap 包含映射到具有特定ID整数值的每个已创建节点的节点指针,而数组 heap 是包含与其当前值相关的节点的堆数组

一切似乎都有效,但是,我的pq_free函数似乎会导致错误或者没有正确释放数组。任何帮助将不胜感激

结构

typedef struct node_struct{
  int ID;
  double val;
}NODE;

struct pq_struct {
  char heapType;
  int max;
  int inUse;
  NODE ** heap;  //BOTH have a specific capacity
  NODE **heapMap; //array of pointers to each 
};

这是我用来为结构分配内存的函数。

    PQ * pq_create(int capacity, int min_heap){


  PQ * newQueue = (PQ*) malloc(sizeof(PQ)); //Allocate memory for a new heap
  newQueue->max = capacity;
  newQueue->inUse = 0;
  int inUse = 1;//1 in use by default, the 0th point in the array is left alone intentionally

  //If min_heap == 0, it it is a max heap, any other value is a min heap.
  if(min_heap != 0){
    newQueue->heapType = 'm';
  }else{
    newQueue->heapType = 'M';
  }

  //Allocate memory for heapMap and heap..

  newQueue->heap = (NODE**) malloc(sizeof(NODE*)*capacity); //array of nodes, the heap


  newQueue->heapMap = (NODE**) malloc(sizeof(NODE*) * capacity);//array of node pointers, the HEAPMAP
  int i = 0;
  for (i = 0; i < capacity + 1;i++) {
      newQueue->heapMap[i] = NULL;
  }

  //return PQ pointer

  return newQueue;
}

这是我的pq_free函数似乎无法正常工作。提前感谢您的帮助。

 void pq_free(PQ * pq){
 //free all nodes

 NODE * temp;
 NODE ** temp2;
 int i;
 for (i = 0; i < pq->inUse; i++) {
     if (pq->heapMap[i] != NULL) {
         temp = pq->heapMap[i];
         free(temp);

     }
 }
 //pq->heapMap = NULL;
 free(pq->heap);
 free(pq->heapMap);
 free(pq);


}

1 个答案:

答案 0 :(得分:0)

由于我曾经在这个网站上被骂过,我觉得有义务对你做同样的事情。您不应该强制转换malloc,因为它会自动转换为指定的数据类型,并可能导致一些不良情况。

除了那个单独的节点如何分配?具体是什么错误?我认为你在分配容量时也会离开你的heapMap,但是迭代容量+ 1个元素。