首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ 結構體嵌套動態數組的內存釋放正確姿勢:分級 delete[] 避免洩漏

     編輯:程式設計疑難解答

結構定義

struct Link_Info {
    int Destination_VertexID;
    int Vertex_To_Vertex_LinkID;
    int Cost_of_Link;
};

struct Vertex_Info {
    int OutDegree;
    int Vertex_Num;
    Link_Info* out = new Link_Info[8]; // 內層動態數組
};

Vertex_Info* Vertex_Chain = new Vertex_Info[600]; // 外層動態數組

正確釋放順序

void FreeVertexChain(Vertex_Info* chain, int count) {
    if (!chain) return;
    for (int i = 0; i < count; ++i) {
        delete[] chain[i].out;   // 1. 先釋放每個元素的內層數組
        chain[i].out = nullptr;
    }
    delete[] chain;              // 2. 再釋放外層數組
    chain = nullptr;
}

// 調用
FreeVertexChain(Vertex_Chain, 600);

關鍵原則

  1. 分配幾層,釋放幾層,順序相反:先內後外。
  2. 釋放後置空指針,防止二次釋放。
  3. 若構造函數分配內存,析構函數中釋放(RAII),推薦使用 std::vector/std::unique_ptr 自動管理。

現代 C++ 改寫(推薦)


struct Vertex_Info {
    int OutDegree;
    int Vertex_Num;
    std::vector out; // 自動管理內存
};

std::vector Vertex_Chain(600); // 無需手動釋放
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved