C++ delete crashes on certain instances
I have the following C++ method:
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;
}
There is 1 particular instance where the delete[]
call crashes the program, Visual Studio returns the error message:
HEAP CORRUPTION DETECTED: after Normal block (#44325) at 0x01214980 CRT detected that the application wrote to memory after end of heap buffer.
Any ideas?
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
The size of the array is scanYEnd - scanYStart
.
Your loop covers the inclusive range [scanYStart, scanYEnd]
, the size of which is one larger than the array, so you write beyond the allocated memory. You will need to make the array one element larger.
(Off topic, but I would also suggest using std::vector
rather than a manually allocated array, to fix the memory leak when an exception is thrown from this function. You could then use push_back
inside the loop, to avoid having to calculate the size.)
There is at least one problem in this code. Let's suppose scanYStart
is 0 and scanYEnd
is 10. The size of the histogram
array is 10 (10-0). And in the loop for( int y = scanYStart; y <= scanYEnd; y++ ){
iterates from 0 to 10 (including 10), ie 11 iterations. There is a heap corruption in the histogram [ n ]++;
line then n is 10.
上一篇: 带地址的c ++数组迭代
下一篇: C ++在某些情况下删除崩溃