C ++在某些情况下删除崩溃

我有以下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返回错误消息:

HEAP CORRUPTION DETECTED:Normal Block(#44325)at 0x01214980之后CRT检测到应用程序在堆缓冲区结束后写入内存。

有任何想法吗?


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

数组的大小是scanYEnd - scanYStart

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

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


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

链接地址: http://www.djcxy.com/p/82331.html

上一篇: C++ delete crashes on certain instances

下一篇: Can calling memset on a dynamically allocated memory cause heap corruption