C ++删除在某些实例上崩溃

时间:2013-03-29 12:25:02

标签: c++ memory-management

我有以下C ++方法:

void MyClass::FindBottom ( CIppImage& bwImage, FieldRec* obField, int& bottomBorder_top, int& bottomBorder_bottom, int& topBorder_top, int& topBorder_bottom, bool& algoFoundBorder ){

    int scanYStart = topBorder_top + obField->getH() - VERTICAL_SCAN_AMOUNT;
    int scanYEnd = topBorder_top + obField->getH() + ( VERTICAL_SCAN_AMOUNT * 1.5 );
    int scanAmount = scanYEnd - scanYStart;
    int xScanEnd = obField->getOX() + obField->getW();

    int* histogram = new int[ scanAmount ];
    memset ( histogram, 0, (scanAmount) * sizeof(int) );

    Ipp8u* bwDataPtr = bwImage.DataPtr();

    int bwLineWidth = ( bwImage.Width() + 7 ) / 8;
    int n = 0;

    for( int y = scanYStart; y <= scanYEnd; y++ ){
        for( int x = obField->getOX(); x < xScanEnd; x++ ){
            if( ( GETBYTE( bwDataPtr, x, y, bwLineWidth ) ) != 0 && ( GETPIXEL(bwDataPtr, x, y, bwLineWidth ) ) != 0 ){
                histogram [ n ]++;
            }
        }
        n++;
    }

    int numFillPixelsThreshold = (int)(HORIZ_FILL_THRESHOLD * obField->getW());
    vector<int> goodRows;
    for( int j = 0; j < VERTICAL_SCAN_AMOUNT+VERTICAL_SCAN_AMOUNT+1; j ++ ){
        if( histogram[ j ] >= numFillPixelsThreshold ) {
            goodRows.push_back( scanYStart + j );
        }
    }
    if( goodRows.size() > 0 ){
        bottomBorder_top = goodRows[0];
     bottomBorder_bottom = goodRows[goodRows.size()-1];
    algoFoundBorder = true;
    }else{
        bottomBorder_top    = obField->getOY() + obField->getH() - 4;
        bottomBorder_bottom = obField->getOY() + obField->getH() + 4;
        algoFoundBorder = false;
    }
    delete[] histogram;
    histogram = 0;
}

有{1}}调用崩溃程序的一个特定实例,Visual Studio返回错误消息:

  

HEAP CORRUPTION DETECTED:在正常块(#44325)之后的0x01214980处,CRT检测到应用程序在堆缓冲区结束后写入内存。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

数组的大小为scanYEnd - scanYStart

你的循环涵盖了包含范围[scanYStart, scanYEnd],其大小比数组大1,所以你要超出分配的内存。您需要将数组放大一个元素。

(偏离主题,但我还建议使用std::vector而不是手动分配的数组,以便在从此函数抛出异常时修复内存泄漏。然后,您可以在内部使用push_back循环,以避免必须计算大小。)

答案 1 :(得分:1)

int scanAmount = scanYEnd - scanYStart; 
int n = 0; 
for( int y = scanYStart; y <= scanYEnd; y++ ){
   n++;
}
ASSERT(n == scanAmount); // failed, because your for loop makes one more step and as a result you corrupt heap

答案 2 :(得分:0)

此代码中至少存在一个问题。假设scanYStart为0且scanYEnd为10. histogram数组的大小为10(10-0)。并且在循环for( int y = scanYStart; y <= scanYEnd; y++ ){中从0到10(包括10)迭代,即11次迭代。 histogram [ n ]++;行中存在堆损坏,然后n为10.