Search code examples
cpointersportability

Is there a way to determine if the representation of a pointer is 'linear' in C?


In C, there is no guarantee that the behavior of pointer arithmetic reflects the behavior of integer arithmetic if the pointer is converted to an integer, as far as I know. In other words, there is no guarantee that any of the below assertions will hold:

char a[2]; // So that p + 1 is a valid memory location
char *p = a;
assert(p + 1 == (char *)((uintptr_t)p + 1));

int x;
int *p = &x;
assert((intptr_t)p % sizeof(int) == 0);

On most systems these will hold. The trailing bits of the integer representation of a pointer will represent the pointer alignment, and that adding a certain offset to a pointer is the same as adding the offset times the size of the pointer type to the integer representation of the pointer.

However, is there any way to determine, ideally at compile time, whether on any particular implementation, those assumptions will always hold true for any pointer, provided the pointer arithmetic would have produced a valid pointer anyway, since the Standard does not guarantee them? For example, to fail early on unsupported implementations, fallback on an alternative implementation, etc.


Solution

  • Per discussion in comments, the question is whether the specifications of the C standard provide a reliable way to determine whether the assertions will hold true in any particular C implementation. (So the question is not whether a C implementation might provide some way to know this, as by predefining a preprocessor macro that a program could test. The question is whether there is a test that works in all C implementations.)

    The answer is no.

    Since this answer relies on the fact there is nothing for this in the C standard, there is no way to demonstrate it other than referring to the whole of the C standard. I am fairly familiar with the current C standard and believe it does not provide any such mechanism.

    Note 69 to C 2018 6.3.2.2 5 tells us “The mapping functions for converting a pointer to an integer or an integer to a pointer are intended to be consistent with the addressing structure of the execution environment,” but this is not a normative part of the standard, and I believe there is nothing in the standard which says that any information about this mapping should be provided by a C implementation. Nor are there any stated properties of pointers and mappings to integers that would provide tests of whether the assertions always hold.