This is an unofficial snapshot of the ISO/IEC JTC1 SC22 WG21 Core Issues List revision 115d. See http://www.open-std.org/jtc1/sc22/wg21/ for the official list.

2024-10-26


2013. Pointer subtraction in large array

Section: 7.6.6  [expr.add]     Status: drafting     Submitter: Jason Merrill     Date: 2014-10-02

The common code sequence used by most implementations for pointer subtraction involves subtracting the pointer values to determine the number of bytes and then shifting to scale for the size of the array element. This produces incorrect results when the difference in bytes is larger than can be represented by a ptrdiff_t. For example, assuming a 32-bit ptrdiff_t:

  int *a, *b;
  a = malloc(0x21000000 * sizeof(int));
  b = a + 0x21000000;
  printf("%lx\n", (long)(b - a));

This will typically print e1000000 instead of 21000000.

Getting the right answer would require using a more expensive code sequence. It would be better to make this undefined behavior.