0

我有以下 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 个特定实例delete[]调用使程序崩溃,Visual Studio 返回错误消息:

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

有任何想法吗?

4

3 回答 3

1

数组的大小是scanYEnd - scanYStart

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

(题外话,但我也建议使用std::vector而不是手动分配的数组来修复此函数引发异常时的内存泄漏。然后您可以push_back在循环内使用,以避免必须计算大小。)

于 2013-03-29T12:32:14.477 回答
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
于 2013-03-29T12:32:14.827 回答
0

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

于 2013-03-29T12:36:02.087 回答