Throws the structure T * into the behavior of the structure C * undefined if the first field T is C?

When trying to debug the problem that I use Speex with, I noticed that it (well, not only speex, but also the sample code) does the following:

  • Returns a pointer to EncState from the initialization function.
  • Insert this pointer into a void pointer
  • Save void pointer
  • (in the other place)
  • Place void pointer to pointer to pointer to SpeexMode
  • Split pointer

It so happened that the EncState definition begins with a field of type SpeexMode *, so the integer values โ€‹โ€‹of the pointer to the first field and the pointer to the structure are the same. The gap occurs at runtime.

But ... does this language really allow this? Is the compiler free to do whatever it wants if it compiles it? Throws the structure T * into the behavior of the structure C * undefined if the first field T is C?

+5
source share
1 answer

From the C11 standard:

(C11 ยง6.7.2.1.15: "A pointer to a structure object that is appropriately transformed points to its initial member ... and vice versa. It may be an unnamed complement inside the structure object, but not the beginning.")

This means that the behavior you see is allowed and guaranteed.

+7
source

All Articles