What is guaranteed about the size of a function pointer?

Paul Biggar picture Paul Biggar · Oct 15, 2010 · Viewed 17.1k times · Source

In C, I need to know the size of a struct, which has function pointers in it. Can I be guaranteed that on all platforms and architectures:

  • the size of a void* is the same size as a function pointer?
  • the size of the function pointer does not differ due to its return type?
  • the size of the function pointer does not differ due to its parameter types?

I assume the answer is yes to all of these, but I want to be sure. For context, I'm calling sizeof(struct mystruct) and nothing more.

Answer

Oliver Charlesworth picture Oliver Charlesworth · Oct 15, 2010

From C99 spec, section 6.2.5, paragraph 27:

A pointer to void shall have the same representation and alignment requirements as a pointer to a character type. Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

So no; no guarantee that a void * can hold a function pointer.

And section 6.3.2.3, paragraph 8:

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.

implying that one function pointer type can hold any other function pointer value. Technically, that's not the same as guaranteeing that function-pointer types can't vary in size, merely that their values occupy the same range as each other.