2

In the following code, it seems that I can't get the correct address of the second function.
Link to Ideone : http://ideone.com/r07UZc

#include <stdio.h>

class A
{
public:
    __attribute__((noinline)) int func1();
    __attribute__((noinline)) int func2();
};

int A::func1()
{
    return 1;
}

int A::func2()
{
    return 2;
}

int main()
{
    printf("%p %p\n", &A::func1, &A::func2);
    return 0;
}

The printed values are : 0x80484d0 (nil)
The first address seem to be correct but not the second. Why ?

Michael M.
  • 2,556
  • 1
  • 16
  • 26

1 Answers1

2

Pointers to member functions are very weird beasts. They're very rarely just the address of the function's code.

Even if they are, they're still very different types than void* expected by printf, thus printf invokes undefined behavior trying to interpret them as void*.

In your particular case, the reason may be that member function pointers are wider than void* (twice as wide, perhaps?), thus the second %p prints the second part of &A::func1. But it's a mere conjecture – the only thing certain is that it's UB.

Given that there are no facilities in the standard for getting the address from a pointer to member function, it's likely impossible to do that without either compiler-specific hackery, undefined behavior, or both.