2016-04-18 77 views
1

有沒有人看到一些明顯的錯誤與我的展開功能下面?我已經包含了類的私有部分和我的vertex_node結構來提供一些上下文。我不確定它爲什麼沒有正確擴展。任何幫助,將不勝感激。展開功能沒有正確擴展爲我的圖

private: 

//list is pointers to vertex nodes; 

struct vertex_node { 
      string name; 
      set <string> edges; 
}; 

vertex_node **list; 

void Graph:: expand() 
{ 

    int new_cap = capacity * 2+1; 
    //creates new larger array 
    vertex_node **larger_array = new vertex_node*[new_cap]; 

    //loop through all elements of old array 
    for(int i = 0; i<capacity; i++){ 
     if(list[i] != NULL){ 

     //rehash each element and place it in new array 
     int a = hash_string(list[i]->name) % new_cap; 

     larger_array[a]   = new vertex_node; 
     larger_array[a]->name = list[i] -> name; 
     larger_array[a]->edges = list[i] -> edges; 
    } 

    //delete old list 
    delete[] list; 
    list = larger_array; 
    capacity = new_cap; 
    } 
} 
+0

什麼是容量?它是如何初始化的?你能否請嘗試創建一個[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)並向我們展示? –

+2

執行'delete [] list'時,通過'list'的每個元素迭代'i',每次迭代一次,它也被分配到large_array,在下一次迭代時被刪除。但是也許真正的代碼沒有被正確地複製過來。 –

+1

順便說一句,當你分配內存'new'時不會初始化它,如果有一個默認的構造函數,它將被調用,但是指針和其他本地類型(如'int'或'double')沒有默認值構造函數。這意味着當你檢查'list [i]!= NULL'時,你分配的數組中的指針會有* indeterminate *值並給你*未定義的行爲。我建議你做'new vertex_node * [new_cap](nullptr)'將所有指針初始化爲空指針。併爲初始分配做同樣的事情。 –

回答

1

正如我在上面我的評論中提到的,你在第一次迭代結束時使整個數組無效。您嘗試避免內存泄漏值得讚揚,但必須在2個地方完成。

for(int i = 0; i<capacity; i++){ 
      if(list[i] != NULL){ 

      //rehash each element and place it in new array 
      int a = hash_string(list[i]->name) % new_cap; 

      larger_array[a]   = new vertex_node; 
      larger_array[a]->name = list[i] -> name; 
      larger_array[a]->edges = list[i] -> edges; 
     } 

     //clean up every memory location once you're done with it 
     delete list[i]; 
     list = larger_array; 
     capacity = new_cap; 
     } 
    //clean the whole array at the very end 
    delete[] list;