Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Signed integer overflow causes undefined behavior, so nothing can be guaranteed about the program afterward.   The following is one possible scenario that shows why this should be avoided.:

Wiki Markup
The {{size_t}} type is typically represented by the same number of bits as {{int}}, that is, {{sizeof(size_t) == sizeof(int))}}.  In this case, {{n}} might be greater than {{INT_MAX}}.  Assuming quiet wraparound on signed overflow, the loop executes {{n}} times because the comparison {{i < n}} is an unsigned comparison. Once {{i > INT_MAX}}, {{i}} takes on negative values starting with ({{INT_MIN}}).  Consequently, the memory locations referenced by {{p\[i\]}} precede the memory referenced by {{p}} and a write-outside-array bounds occurs.

...

Note that in a preemptive multithreaded program, only one thread is in the infinite loop, so it is still significant that out-of-bounds memory is changed.So, even under the most restrictive of assumptions, there are serious problems with the program. Undefined behavior gives license for the implementation to do anything at all, which could be far worse.

Compliant Solution

Declaring i to be of type rsize_t eliminates the possible integer overflow condition (in this example).  Also, the argument n is changed to be of type rsize_t to document additional validation in the form of a check against RSIZE_MAX.

...