簡體   English   中英

c++ 指向 arrays 指針數組的 int 指針 memory 泄漏

[英]c++ int pointer to array of pointers to arrays memory leaks

所以我有這個 class 和一個 functions.hpp 和一個 functions.cpp

#include "function.hpp"

test::test(int size)
{
    this->size = size;
    matrix = new int*[this->size];
    for (int i = 0; i < size; i++)
    {
        matrix[i] = new int[this->size];
    }
}

test::~test()
{
    for (int i = 0; i < this->size; i++)
        delete[] this->matrix[i];
    
    delete[] this->matrix;
}

但這仍然會產生 memory 泄漏,我正在使用 CRT 庫對此進行測試

#include "function.hpp"
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    int size = 10;
    test test(size);
    _CrtDumpMemoryLeaks();
    return 0;
}

這段代碼仍然向我轉儲 memory 泄漏,我已經學習了幾個教程,我開始懷疑 CRT 庫或我的計算機。

問題是調用_CrtDumpMemoryLeaks之后退出main之前不會調用析構函數。 將您的代碼更改為此

int main()
{
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
    {
        int size = 10;
        test test(size);
    }
    _CrtDumpMemoryLeaks();
    return 0;
}

額外的{}確保在調用_CrtDumpMemoryLeaks之前調用析構函數。

另一種技術是編寫 class 來執行檢查。

class LeakCheck
{
public:
    LeakCheck() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); }
    ~LeakCheck() { _CrtDumpMemoryLeaks(); }
    LeakCheck(const LeakCheck&) = delete;
    LeakCheck& operator=(const LeakCheck&) = delete;
};

int main()
{
    LeakCheck _checker;
    int size = 10;
    test test(size);
    return 0;
}

因為析構函數的調用順序與構造函數相反,所以可以保證_CrtDumpMemoryLeaks會在test的析構函數之后被調用。

我想將LeakCheck稱為墊片 class ,但顯然這不是正確的術語,也許有人可以在評論中告訴我正確的術語。

暫無
暫無

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

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