Run-Time Check Failure #2

来源:互联网 发布:淘宝店铺批量发货 编辑:程序博客网 时间:2024/05/16 02:03

数组越界错误

C/C++是不做数组的越界检查的,一不小心就会发生数组越界的错误,且这类错误在程序运行的时候才会被发现。一旦出错会发生如下的对话框。


如上图所示提示的是数组名为record的数组越界了,提示的行数是在imageprocess.cpp文件中的160行处,此处是一个行数的结束区,也就是说数组越界时,数据会写到越界的位置而不提示,直到函数退出时,收回内存空间时,才会检测到数组越界。

如下代码:
if(Ibw.channels() !=1 )return 0;uchar *pStart = Ibw.ptr<uchar>(0);int Row = Ibw.rows, Col = Ibw.cols;int record[10] = {0};const int unit = Col/10 +1;(修改过后)for(int row=scope; row<Row; row++){bool startCount=false;int count = 0;for(int col=0; col<Col; col++){if(!startCount && *(pStart+ row*Col + col) == frontPixel){startCount = true;record[col/unit] = 1;}if(startCount && *(pStart + row*Col + col) == 255-frontPixel){startCount = false;count++;}}int sum =0;for(int i=0; i<10;i++)sum += record[i];if(count >= hopcount && sum >= distribution){return row-scope;}}return 0;

两处加红的代码,第一处根据图像的宽度来确定一个单位的长度,同时由于是取整运算,所以得到的单元宽度unit*10 < width(图像的宽度)。如果最后的像素是黑色的,在第二个红色区域得到的索引就是10,超出了数组的界。所以要在第一处红色位置,求单元宽度处要加一。













0 0
原创粉丝点击