2013-07-25 31 views
1

我有一個函數如下:OpenCV的錯誤:內存不足,在函數調用

void foo(){ 
    Mat mat(50000, 200, CV_32FC1); 

    /* some manipulation using mat */ 

    } 

然後經過多次循環(在每個循環中,我稱之爲foo()一次),它給出了一個錯誤:

OpenCV Error: insufficient memory when allocating (about 1G) memory.

據我瞭解,Mat是本地的,一旦foo()返回,它會自動解除分配,所以我想知道爲什麼它會泄漏。

它泄漏了一些數據,但不是全部。

這裏是我的實際代碼:

bool VidBOW::readFeatPoints(int sidx, int eidx, cv::Mat &keys, cv::Mat &descs, cv::Mat &codes, int &barrier) { 
    // initialize buffers for keys and descriptors 
    int num = 50000; /// a large number 
    int nDims = 0; /// feature dimensions 


    if (featName == "STIP") 
     nDims = 162; 

    Mat descsBuff(num, nDims, CV_32FC1); 
    Mat keysBuff(num, 3, CV_32FC1); 
    Mat codesBuff(num, 3000, CV_64FC1); 

    // move overlapping codes from a previous window to buffer 
    int idxPre = -1; 
    int numPre = keys.rows; 
    int numMov = 0; /// number of overlapping points to move 

    for (int i = 0; i < numPre; ++i) { 
     if (keys.at<float>(i, 0) >= sidx) { 
      idxPre = i; 
      break; 
     } 
    } 

    if (idxPre > 0) { 
     numMov = numPre - idxPre; 
     keys.rowRange(idxPre, numPre).copyTo(keysBuff.rowRange(0, numMov)); 
     codes.rowRange(idxPre, numPre).copyTo(codesBuff.rowRange(0, numMov)); 
    } 

    // the starting row in code matrix where new codes from the updated features to add in 
    barrier = numMov; 

    // read keys and descriptors from feature file 
    int count = 0; /// number of new points that are read in buffers 
    if (featName == "STIP") 
     count = readSTIPFeatPoints(numMov, eidx, keysBuff, descsBuff); 

    // update keys, descriptors and codes matrix 
    descsBuff.rowRange(0, count).copyTo(descs); 
    keysBuff.rowRange(0, numMov+count).copyTo(keys); 
    codesBuff.rowRange(0, numMov+count).copyTo(codes); 

    // see if reaching the end of a feature file 
    bool flag = false; 

    if (feof(fpfeat)) 
     flag = true; 

    return flag; 
} 
+1

您發佈的代碼不足以[重現問題](http://SSCCE.org)。請發佈一個簡單的示例,但是會演示內存泄漏。 – Aurelius

回答

1

你不要張貼調用你的函數的代碼,所以我不能說這是否是一個真正的內存泄漏。您在readFeatPoints()中分配的Mat對象將被正確解除分配,因此沒有我能看到的內存泄漏。您可以申報Mat codesBuff(num, 3000, CV_64FC1);。與num = 5000,這意味着你正試圖在一個大塊中分配1.2千兆字節的內存。還有些這個數據複製到codes與線:

如果迭代之間numMove + count的值發生變化,這將導致數據緩衝區的重新分配codes。如果該值足夠大,則可能還會消耗大量的內存,這些內存在迭代循環中持續存在。這兩件事情可能會導致heapfragmentation。如果在任何時候都不存在等待的1.2 GB內存塊,則會發生內存不足錯誤,這是您所經歷的。