5
votes

In c99, my understanding is that comparing two pointers which do not point within the same aggregate results in undefined behavior. Given an aggregate A, a pointer p_good which is known to point within A, and a pointer p_unknown which may or may not point within A, is it possible to construct a portable test with defined behavior which determines whether it is safe to compare p_good and p_unknown?

Obviously, this test cannot itself fall afoul of the restrictions on comparing pointers.

I suspect that the answer is 'no', but I'd be happy to be shown otherwise.

1
What do you mean by 'aggregate'? And what are you exactly trying to achieve? - Michał Górny
Do you have a pointer to A? Or just two pointers that point into A? - James McNellis
@eq there is no UB in comparing pointers from distinct arrays for equality, but it is UB to compare pointers from distinct arrays for inequality, i.e. <, <=, >, >=. - Ambroz Bizjak
If you have an array and a candidate pointer, you can compare (==) this pointer to each possible element pointer, and see if it is equal to any of them. So, technically, the answer is yes :) - Ambroz Bizjak

1 Answers

5
votes

You commented:

Another way to frame the question would be like this: Given the definition of an aggregate 'A' and a pointer p, is it possible to answer the question 'does p point within A' without violating the rule on inequality testing of pointers to different aggregates

The only way I can interpret this meaningfully is that you either have an object of type Aggregate type or a pointer to one. Then the answer is simple:

Pseudo-code:

bool p_in_A = false;
for (each element in Aggregate A)
    if (&element == p)
        p_in_A = true;

There is no way to tell whether a stray pointer belongs to an unknown aggregate object (or points to "between" elements in an aggregate).