Signed integer overflow is undefined behavior.
GCC can make signed integer overflow defined, but that causes a slowdown.
Really, the root cause of the bug was making the counter a signed variable, as it doesn't really make sense for a counter to have negative values.
