问题
I have implemented an AVL tree in C. Only later did I read that pointer comparison is only valid between objects in the same array. In my implementation, I do certain equality tests. For example, to test whether a node is a right child of a parent I might test node==node->parent->right
. However, the nodes are allocated as needed, not in a contiguous chunk. Is this behavior defined? How would you write this code instead if it is not?
回答1:
For equality and inequality, in the standard (ISO/IEC 9899:2011) §6.5.9 Equality Operators ¶6 says:
Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.
There's no undefined behaviour in comparing pointers to unrelated objects for equality or inequality.
By contrast, §6.5.8 Relational Operators ¶5 says:
When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object types both point to the same object, or both point one past the last element of the same array object, they compare equal. If the objects pointed to are members of the same aggregate object, pointers to structure members declared later compare greater than pointers to members declared earlier in the structure, and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values. All pointers to members of the same union object compare equal. If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. In all other cases, the behavior is undefined.
This means that comparing pointers with >
, >=
, <
or <=
when the pointers are not pointing to the same object (for the definition of 'same object' given in painstaking detail in the quote), the behaviour is undefined.
来源:https://stackoverflow.com/questions/34973553/c-compare-pointers-from-different-allocations