Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> > For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

> I don't see any way to read these as not requiring the pointers to compare as equal if the compiler happens to put a and b adjacent in memory in the right order and with no padding between them, other than resorting to something ridiculous like claiming that "follow" or "immediately" follow are not defined in the spec and so one object occupying that very next available address after another does not necessarily "immediately follow". This seems to be what the gcc developers went with to declare this is not a bug.

"These operators" in the spec refer to the (additive) pointer arithmetic operators, not the equality operator. So incrementing a pointer to int behaves as if the pointee were in an array of length one, but that does not mean any subsequent equality operator should consider the objects as arrays.

It's totally fine for the equality comparison to return false when the objects in question are actually not arrays.



Then let's make them real arrays:

  #include <stdio.h>

  #define N 8

  int main(void) {
    int a[N], b[N];
    int *p = &a[0];
    int *q = &b[N];
    printf("%p %p %d\n", (void *)p, (void *)q, p == q);
    return 0;
  }
Results:

  $ gcc -std=c11 -O1 ar.c; ./a.out
  0x7ffd32d048c0 0x7ffd32d048c0 0
  $ gcc -std=c11 ar.c; ./a.out
  0x7ffe3f8ccd60 0x7ffe3f8ccd60 1


BTW, things work correctly when the objects live inside a real array:

  #include <stdio.h>

  int main(void) {
    int arr[16];
    int *p = &arr[0] + 1;
    int *q = &arr[1];
    printf("pointers: %p %p %d\n", p, q, p == q);
    return 0;
  }
The result is perfectly correct and predictable, as the Standard guarantees pointer comparisons in this case:

  pointers: 0x71b35ac790d4 0x71b35ac790d4 1
The original code in the article relies on UB, I think, so all bets are off.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: