2

Is it guaranteed, in C, that any pointer type can round-trip through void * successfully?

That is, something like the following guaranteed to work:

typedef struct {
...
} A;

A *p = ...;
void *v = p;
A *p2 = v;
// use p2 here

No matter what the type of A?

SODIMM
  • 303
  • 2
  • 12

1 Answers1

6

Object pointers can indeed be round-tripped through void*. From C11 6.3.2.3 paragraph 1:

A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

Note that the opposite direction is not true, when you convert a void pointer to some object pointer and back you are not guaranteed the same value as what you started with.

Note also that this is not true of function pointers; however, all function pointer types are mutually round-trippable: Paragraph 8 says:

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer.

Moreover, object pointers are also round-trippable among themselves (not involving void pointers), subject to some constraints, by paragraph 7:

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned) for the referenced type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Suggest detailing that round-tripping through `void*` yields an equivalent pointer, not necessarily the _same_ bit-pattern pointer though. IAC, it looks like OP is only interested in equivalent access. – chux - Reinstate Monica Feb 17 '17 at 03:00
  • Pointer to any type may be converted to any other type and back and it will compare equal to the original pointer, as long as alignment isn't violated. – 2501 Feb 17 '17 at 20:04
  • @2501: Citation needed. – Kerrek SB Feb 17 '17 at 20:13
  • Read the 7th paragraph. – 2501 Feb 17 '17 at 20:15
  • @2501: Ah yes, indeed. – Kerrek SB Feb 17 '17 at 20:35
  • @2501: Does anything in the Standard require that an implementation yield a pointer that actually *behaves* like the original pointer, or could a deliberately-obtuse-but-conforming implementation satisfy the stated requirement with a pointer that reports itself as equal to every other pointer but launches nasal demons if code tries to dereference it? – supercat Feb 17 '17 at 21:34