Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sizeof a void (*)() function pointer in C

Tags:

c

To aid with some precise memory allocation that I'm doing in C, I'm trying to get the sizeof a function pointer for a function with return type void that takes no parameters.

However, when I do sizeof (void (*)()), I generate a compiler warning:

function declaration isn’t a prototype [-Wstrict-prototypes]

How do I get the size that I'm looking for?

like image 727
m81 Avatar asked Jul 11 '26 14:07

m81


2 Answers

That is an old style function definition, it is missing the argument list, so add them:

sizeof( void(*)(void) )
like image 121
2501 Avatar answered Jul 14 '26 09:07

2501


For readability purposes, I recommend declaring a type for the signature of any function you'll want have some pointer to:

 typedef void my_sigt(void);

then, to declare a pointer to such a function, code:

 my_sigt* funptr;

and to get its size code sizeof(my_sigt*) (or sizeof(funptr) if you have such a variable funptr)

BTW, I am not sure that the C99 standard guarantees that every function pointer has the same size (or has the same size as some data pointer). But POSIX requires that (in particular, to be able to use dlsym for dynamic linking of such functions).

like image 39
Basile Starynkevitch Avatar answered Jul 14 '26 09:07

Basile Starynkevitch