Is it UB to compare (for equality) a void pointer with a typed pointer in C?

207 views Asked by At

I have a typed pointer, typed, that was initialized using pointer arithmetic to point to an object within an array. I also have a function that takes two pointer args, the 1st typed the same as the afore-mentioned pointer and the 2nd is void * (see myfunc() in the code below).

If I pass typed as the 1st argument and another pointer typed the same as typed as the 2nd argument, and then compare these for equality within the function, is that Undefined Behavior?

#include <stdio.h>

typedef struct S {int i; float f;} s;

void myfunc(s * a, void * b)
{
  if (a == b)  // <-------------------------------- is this UB?
    printf("the same\n");
}

int main()
{
  s myarray[] = {{7, 7.0}, {3, 3.0}};
  s * typed = myarray + 1;
  myfunc(typed, &(myarray[0]));

  return 0;
}

Update: Ok, so I come back a day after posting my question above and there are two great answers (thanks both to @SouravGhosh and @dbush). One came in earlier than the other by less than a minute (!) but from the looks of the comments on the 1st one, the answer was initially wrong and only corrected after the 2nd answer was posted. Which one do I accept? Is there a protocol for accepting one answer over the other in this case?

2

There are 2 answers

6
dbush On BEST ANSWER

This comparison is well defined.

When a void * is compared against another pointer type via ==, the other pointer is converted to void *.

Also, Section 6.5.9p6 of the C standard says the following regarding pointer comparisons with ==:

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 is no mention here of undefined behavior.

1
Sourav Ghosh On

No, this is not undefined behaviour. This is allowed and explicitly defined in the spec for equality operator constraints. Quoting C11, chapter 6.5.9

one operand is a pointer to an object type and the other is a pointer to a qualified or unqualified version of void;

and from paragraph 5 of same chapter

[...] If one operand is a pointer to an object type and the other is a pointer to a qualified or unqualified version of void, the former is converted to the type of the latter.