I’m having a strange issue. I have a dynamically created 2D array, Content, which has height of _h and width of _w (in my implementation, row is a first parameter and column is second, makes sense in context). Two indexes CAN be out of bounds, that’s so by design and if it’s so, then the indexes are “wrapped around” the array:
Content[v.iget()%_h][u.iget()%_w];
v and u are objects of my own class; they have an __int64 value inside and iget() goes like this:
return value>>precision;
It returns a usual 32-bit int. I “wrap” this int value by height or width with %, and obviously the remainder is always 0 <= r < max. So this % operation also provides a protection against any possible out-of-bounds situations, BUT I sometimes get the access violation exactly on this line. When I look at values of v and u, they’re something like -7753978124 – actually, having a negative number in my context isn’t supposed to happen (so I have yet to look for what’s causing it), but anyway, .iget() should turn it into a normal integer and %_h or %_w should put it into the bounds, but instead I get access violation. How can this be possible?
Nope.
(-1 % 2) == -1so expression
x % maxwill return values in range of (-max..max).That’s the first problem.
The second problem is this:
0xffffffff00000000 >> 32is0xffffffff, which is a negative number-1(for signed 32bit int, that is).You can fix the problem by using expressions like this:
((x % width) + width)%widthOR you could fix index with if/else:
Alternatively you could make iget() return
unsigned int, but this will not wrap around negative indexes properly for all widths and heights that are not power of 2.