Paul Paul - 2 months ago 5x
C Question

Subtraction of non-divisible pointer addresses

Is subtraction of non-divisible pointer addresses defined in C? In C++?

Here's an example:

void* p = malloc(64);

int* one = (int*)((char*)p);
int* two = (int*)((char*)p + 7);

printf("%x %x %d %d\n", one, two, sizeof(int), two - one);

Ideone link.

I get the output
8a94008 8a9400f 4 1
, so it seems like it does the division and truncates the remainder. Is the behavior defined?


This is undefined behavior according to 5.7.6:

When two pointers to elements of the same array object are subtracted, the result is the difference of the subscripts of the two array elements. [...] Unless both pointers point to elements of the same array object, or one past the last element of the array object, the behavior is undefined.

In your code, pointer two is not pointing to an element of the same int array as pointer one. In fact, it is not pointing to any array element of p, because it points to the "middle" of one of the elements (which in itself is an undefined behavior).