Don't rely on the behaviour of signed integer overflows

It is unspecified. Instead, use an unsigned type.
There should really be a better limit than just INT_MAX, but use that as
the code was already trying to limit it to it.

Additionally, check that another variable that is used as an array
accesor is not greater than the size of the buffer.