Pointers with different provenance can be equal in a recent version of gcc:
// test.c
#include <stdio.h>
int a[4];
int b[4];
int main() {
puts(a+4 == b ? "equal" : "inequal");
return 0;
}
$ gcc --version
gcc (GCC) 13.2.1 20230801
$ gcc test.c && ./a.out
equal
Is this behavior conformant with the c standard?
This is allowed to happen, but it's not guaranteed.
Section 6.5.9p6 of the C standard regarding the equality operator states:
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.109)
...
- Two objects may be adjacent in memory because they are adjacent elements of a larger array or adjacent members of a structure with no padding between them, or because the implementation chose to place them so, even though they are unrelated. If prior invalid pointer operations (such as accesses outside array bounds) produced undefined behavior, subsequent comparisons also produce undefined behavior
Some compilers may have knowledge of pointer provenance and can use that knowledge to decide whether or not such a comparison is true.
See also: Can an equality comparison of unrelated pointers evaluate to true?
Does this behavior conformant with the c standard?
The provenance of pointer values does matter in some circumstances, but the C language makes no requirement or guarantee that pointers with unrelated provenance must compare unequal. On the contrary, it 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.
(C17 6.5.9/6; emphasis added)
It clarifies that:
Two objects may be adjacent in memory because they are adjacent elements of a larger array or adjacent members of a structure with no padding between them, or because the implementation chose to place them so, even though they are unrelated.
(C17 footnote 111)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With