簡體   English   中英

在優先級隊列的c實現中取消分配結構指針數組

[英]deallocating array of struct pointers in c implementation of priority queue

我在為實現的優先級隊列釋放結構指針數組時遇到問題。 我從客戶端c程序中創建了兩個具有固定大小的節點指針的動態數組。 數組heapMap包含節點指針,這些節點指針使用特定的ID整數值映射到每個創建的節點,而數組是包含節點當前值的堆數組。

一切似乎都正常,但是我的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);


}

由於曾經在此站點上受此困擾,所以我有義務對您做同樣的事情。 您不應該轉換malloc,因為它會自動轉換為分配的數據類型,並可能導致某些不良情況。

除此之外,各個節點如何分配? 具體會給出哪些錯誤? 我認為您在分配容量時也要退出heapMap,但是要在容量+1個元素上進行迭代。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM