Search code examples
cfunction-pointers

How to format a function pointer?


Is there any way to print a pointer to a function in ANSI C? Of course this means you have to cast the function pointer to void pointer, but it appears that's not possible??

#include <stdio.h>

int main() {
    int (*funcptr)() = main;

    printf("%p\n", (void* )funcptr);
    printf("%p\n", (void* )main);

    return 0;
}

$ gcc -ansi -pedantic -Wall test.c -o test
test.c: In function 'main':
test.c:6: warning: ISO C forbids conversion of function pointer to object pointer type
test.c:7: warning: ISO C forbids conversion of function pointer to object pointer type
$ ./test
0x400518
0x400518

It's "working", but non-standard...


Solution

  • The only legal way to do this is to access the bytes making up the pointer using a character type. Like this:

    #include <stdio.h>
    
    int main() {
        int (*funcptr)() = main;
        unsigned char *p = (unsigned char *)&funcptr;
        size_t i;
    
        for (i = 0; i < sizeof funcptr; i++)
        {
            printf("%02x ", p[i]);
        }
        putchar('\n');
    
        return 0;
    }
    

    Examining the bytes of the function pointer with an lvalue of type void *, or any non character type, is undefined behaviour.

    What those bytes making up the function pointer actually mean is implementation-dependent. They could just represent an index into a table of functions, for example; or they could even be the first N characters of the function's name which is looked up in the symbol table when you call through the function pointer. The only operations that need be supported on a function pointer are calling the function through it and comparison against another function pointer or NULL for strict equality/inequality, so there is very wide latitude available in how they are implemented.