1. 程式人生 > >C++ 動態多維數組的申請與釋放

C++ 動態多維數組的申請與釋放

一段 內容 row 像素 這樣的 delet count ros body

今天在實驗室的項目中遇到了一個問題,直接上代碼:

   void ViBe::init(Mat img)
    {
        imgcol = img.cols;
        imgrow = img.rows;
        // 動態分配三維數組,samples[][][num_samples]存儲前景被連續檢測的次數
        // Dynamic Assign 3-D Array.
        // sample[img.rows][img.cols][num_samples] is a 3-D Array which includes all pixels‘ samples.
samples = new unsigned char **[img.rows]; for (int i = 0; i < img.rows; i++) { samples[i] = new uchar *[img.cols]; for (int j = 0; j < img.cols; j++) { // 數組中,在num_samples之外多增的一個值,用於統計該像素點連續成為前景的次數; // the ‘+ 1‘ in ‘num_samples + 1‘, it‘s used to count times of this pixel regarded as foreground pixel.
samples[i][j] = new uchar[num_samples + 1]; for (int k = 0; k < num_samples + 1; k++) { // 創建樣本庫時,所有樣本全部初始化為0 // All Samples init as 0 When Creating Sample Library. samples[i][j][k] = 0; } } } FGModel
= Mat::zeros(img.size(), CV_8UC1); }

這段代碼是我在Github上面直接下載的,是一段ViBe背景建模的代碼。代碼的內容是分配圖像各個點sample的數組,也就是說每個點有一個樣本集,總共是cols*rows*sample_num個數值,所以做成了一個三維數組的形式。

問題出現在析構上面。一開始我沒有看代碼是怎麽寫的,直到有一個測試視頻,因為鏡頭大範圍的晃動,按照流程多次重建了ViBe背景,出現了內存不足而崩潰的問題。

首先想到的就是動態分配的數組沒有正確析構。看原本的析構代碼:

void ViBe::deleteSamples()
{
    delete samples;
}

ViBe::~ViBe()
{
    deleteSamples();
}

這樣的寫法並不能正確釋放申請的內存。具體原因,我猜測可能是因為申請到的內存並不是連續的,從而這樣只能釋放掉一個二重指針組成的數組。

正確的做法,應該是按照與申請內存相反的方向進行釋放,代碼如下:

void ViBe::deleteSamples()
    {
        for (int i = 0; i < imgrow; i++)
        {
            for (int j = 0; j < imgcol; j++)
            {
                delete samples[i][j];
            }
            delete samples[i];
        }
        delete[] samples;
    }

這樣就不會出現內存泄漏的問題了!

C++ 動態多維數組的申請與釋放