[Solved] Decrementing a pointer with an unsigned “negative” number


[Edit] This is the answer to a previous version of the question, which showed the problem in action when calling these functions with argument dist==1

-(unsigned long)1 is well-defined and wraps around. It’s just ULONG_MAX. For the same reason, -(unsigned int) is UINT_MAX.

Pointer arithmetic outside array bounds causes Undefined Behavior, so it’s perfectly reasonable for GCC to just ignore the possibility. They can treat an pointer on x64 as just a 64 bit integer with wrap-around, for instance. Adding a 64 bits ULONG_MAX to a 64 bits pointer with wrap-around just decreases the pointer by -1, that’s how wrap-around works. Adding a 32 bits UINT_MAX points nowhere near your int[100].

So, the behavior you see is one completely valid consequence of Undefined Behavior. It however is totally unreliable. An optimizer may know that you can’t add more than the maximum number of elements permitted in an array (which for 4 byte ints on a 64 bit platform would be 2^62), and make assumptions from there on.

8

solved Decrementing a pointer with an unsigned “negative” number