Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can loop index run out of loop bound

Tags:

c++

c

Recently, I ran into a problem of iterations running out of loop bound. By logging, I found that the loop index cannot be bounded by the loop bound.

After further debugging, I have figured out that it was because an out-of-range write to cross_parray occured somewhere before the code snippet attached following:

cv::Point2f cross_parray[8];
int cross_points_num = 0;
int j;

// ...

for(j = 0; j < cross_points_num; j++)
{
  printf("%d   Cross[%d]: %f %f\n", cross_points_num, j, cross_parray[j].x, cross_parray[j].y);
}        

Here is the outputs by the above printf:

9   Cross[1718]: 239764258816.000000 0.049635
9   Cross[1719]: 56350172250112.000000 3277795840.000000
9   Cross[1720]: 245523097321472.000000 817.286072
9   Cross[1721]: 810850240.000000 0.000000
9   Cross[1722]: 4630804223985380483294822400.000000 17845644235931175201275904.000000
9   Cross[1723]: 279783113978270150157139968.000000 217149087997375045783066247168.000000
9   Cross[1724]: 16965729398885974016.000000 75876376993756550538537486778368.000000
9   Cross[1725]: 1125715943805045169979392.000000 257558259045784092672.000000
9   Cross[1726]: 71920725395007019893418622976.000000 263079777742056587264.000000
9   Cross[1727]: 18063601952671647256054595584.000000 17857709399654295200260188798976.000000
9   Cross[1728]: 286724012145286700981684214431744.000000 0.000000
9   Cross[1729]: 1157838373559229814725935104.000000 261926873829635784704.000000
9   Cross[1730]: 0.000000 0.000000
9   Cross[1731]: 0.000000 0.000000

Why an out-of-range error would cause such a weird execution that loop index run out of loop bound?

like image 244
Shindou Avatar asked Nov 25 '19 12:11

Shindou


2 Answers

That's probably because cross_points_num is declared right after cross_parray; they are located in neighboring memory areas, so writing into cross_parray[8] (which is out of bounds for that particular array) is equivalent to writing at the location of cross_points_num.

If cross_parray was a notebook, writing beyond the limit of the last page would be like writing on the desk itself.

like image 92
Alexandre Vinçon Avatar answered Sep 19 '22 01:09

Alexandre Vinçon


Once undefined behaviour occured in your program all bets are off (aka you are in UB land). Writing out-of-bounds can in practice potentially overwrite another variable and lead to unpredictable result for anything that happens after the out-of-bounds access.

like image 30
463035818_is_not_a_number Avatar answered Sep 21 '22 01:09

463035818_is_not_a_number