Section 4.25

Pointer arithmetic

Definition

Pointer arithmetic is adding an integer to a pointer, subtracting an integer from it, or subtracting one pointer from another. In C the unit is one element of the pointed-to type: if p points to a 4-byte int, then p + 1 lies 4 bytes further on, and the difference of two pointers counts elements, not bytes. C defines pointer arithmetic only within one array §14.5, where a single object counts as an array of one element, and at the position just past its last element. Any other result is undefined behavior §4.12.

The idea

A program walks through an array of records one record at a time. With pointer arithmetic the step is written p + 1 whatever the size of a record, because C scales the step by the element size: for 4-byte elements p + 1 is 4 bytes on, for 12-byte elements 12 bytes on. Array indexing is built on the same idea: C defines a[i] as *(a + i), the element i positions after the start.

The second idea is the boundary. A pointer is like a bookmark that may move to any page of one book, and to the space just after the last page, where it marks the end without pointing at a page; it may never move into another book or before the first page. The space after the last page lets loops stop: a loop runs while p != a + n, so a + n must be a legal value although no element is there. The picture stops being accurate on ordinary hardware, where nothing physically stops the bookmark. The boundary is a rule that the compiler assumes the program obeys, and it optimizes on that assumption.

How it works

Let p point to element ii of an array of NN elements of type T, and let ss be sizeof(T), the size of one element in bytes.

  1. Adding an integer. p + n points to element i+ni + n, at an address n⋅sn \cdot s bytes further on. The result must lie between element 0 and the one-past position NN, both included.

  2. Subtracting an integer. p - n points to element i−ni - n, under the same condition. There is no position before element 0.

  3. Subtracting two pointers. If q points to element jj of the same array, p - q equals i−ji - j, counted in elements. The result has type ptrdiff_t, a signed integer type, and must fit in it.

  4. Comparing. Equality can compare pointers to compatible types even when the objects belong to separate allocations. For different object types, convert both pointers to void * first. Within an array, compatible pointers sort in element order up to the one-past position. Within one structure, compatible pointers to later members compare greater. Pointers of compatible types to members of one union compare equal.

  5. Dereferencing. *p is allowed only at positions 0 to N−1N - 1. The one-past position may be formed, compared and subtracted, but never read or written.

A single object that is not an array counts as an array of one element, so &x + 1 is the one-past position of x. To move by bytes rather than elements, convert the pointer to unsigned char *; the bytes still belong to the same object, and the same bounds apply.

Worked example

Take an array int a[8] whose first element is at address 0x20000100, with 4-byte int. The array covers 8×4=328 \times 4 = 32 bytes, from 0x20000100 to 0x2000011F.

The boundary matters most in a length check. A parser reads a 64-byte buffer of unsigned char at 0x20000100. It keeps cur, a pointer to the next unread byte, and end, the one-past pointer 0x20000140. After 60 bytes cur is 0x2000013C, and a message claims a length len of 0xFFFFFFF0, which is 4,294,967,280, on a 32-bit processor.

Stated precisely

Let p point to element ii of an array object of NN elements of type T, with 0≤i≤N0 \le i \le N, where i=Ni = N is the one-past position and an object that is not an array counts as N=1N = 1. Let ss be sizeof(T) in bytes, let addr(p)\mathrm{addr}(p) be the address that p holds, and let nn be an integer. Section 6.5.6 of C11, the 2011 edition of the C standard, gives:

Section 6.5.2.1 defines a[k] as *(a + k), so every subscript obeys the same bounds. Section 6.5.8 gives the ordering rules for pointers to compatible object types. Section 6.5.9 permits equality comparisons between pointers to compatible types (possibly differently qualified), between an object pointer and a pointer to qualified or unqualified void, or between a pointer and a null pointer §4.26 constant.

Limits and common mistakes

The unit is elements, not bytes. Adding a byte count to an int pointer moves 4 times too far when int has 4 bytes. Convert byte lengths to elements, or work through an unsigned char pointer.

Forming the pointer is already the error. An out-of-range pointer is undefined even if nothing reads through it, so a check must compare lengths or indices before any pointer is computed, as in the overflow-safe range check above.

The rows of a two-dimensional array are separate arrays. For int m[3][4], &m[0][0] + 4 is the one-past position of row 0, and reading m[1][0] through it is undefined although that element sits at that address. The list of undefined behaviors in C11 gives a similar case.

Arithmetic on void * is not standard C. Some compilers accept it as an extension that treats the element size as 1; portable code converts to unsigned char * first.

A null pointer is not an array. Even adding 0 to a null pointer is undefined in C11.

Machine code sees plain numbers. At the instruction level any two addresses can be subtracted or compared. The restrictions are rules of C that an optimizing compiler relies on; a check on uintptr_t integers, or in assembly language, follows the processor’s rules instead and is not portable C.

Questions answered

Can subtracting pointers from unrelated allocations be used as a portable check?

No. C defines the difference p - q of two pointers only when both point into the same array object, or just past its last element; for pointers into two separate allocations the behavior is undefined (C11 section 6.5.6), meaning the standard places no requirement on the program. In practice three things go wrong. On a processor with one flat address space the machine still subtracts the two addresses, but the result depends on where the allocator happened to place the blocks, so it says nothing about which object a pointer belongs to. An optimizing compiler may assume the subtraction never happens and transform the surrounding code on that assumption. And on machines with segmented memory, such as 16-bit x86 programs where an address is a segment number plus an offset, the two addresses need not lie in one numeric space at all. The ordering operators also give no portable order for separate allocations. They do order compatible pointers to members of the same structure by declaration order.

A portable check keeps each offset together with the object it belongs to. Store each buffer’s base pointer and length, and test that an offset is smaller than the length, or compare a requested length with the remaining space end - cur, which subtracts two pointers into the same buffer. An equality comparison on compatible pointers can tell whether they compare equal. Membership in a particular buffer still requires a separate argument.

Related entries: Overflow-safe range check (§4.17), Pointer provenance (§4.24), Object lifetime (§4.1), Buffer overflow (§4.4), Out-of-bounds read (§4.5), Null pointer (§4.26). Further reading: [78].