Title
Pointer subtraction in large array
Status
drafting
Section
7.6.6 [expr.add]
Submitter
Jason Merrill

Created on 2014-10-02.00:00:00 last changed 116 months ago

Messages

Date: 2014-10-02.00:00:00

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.

History
Date User Action Args
2014-10-02 00:00:00admincreate