0

As far as i know "offsetof" macro is defined as :

#define offsetof(st, m) ((size_t)(&((st *)0)->m))

based on this link : http://en.wikipedia.org/wiki/Offsetof

So I write my own code snippet to calculate offset of a struct members:

typedef struct{
    char a;
    int b;
    int c;
}example_struct;

int main(int argc, char *argv[])
{
    example_struct *p = 0;

    printf("%p\n", &(p->a));        --> 00000000
    printf("%p\n", &(p->b));        --> 00000004
    printf("%p\n", &(p->c));        --> 00000008

    printf("%p\n", &(p->a));        --> 0
    printf("%p\n", &(p->b));        --> 4
    printf("%p\n", &(p->c));        --> 8

    cout << &(p->a);        --> this line cause crash ???
    cout << &(p->b);        --> 00000004
    cout << &(p->c);        --> 00000008

    cout << (unsigned int)&(p->a);        --> 0
    cout << (unsigned int)&(p->b);        --> 4
    cout << (unsigned int)&(p->c);        --> 8

    return 0;
}

My questions are:

  • Does the type-cast cause the crash. Why can`t cout the offset of the first member but printf can?
  • Why should we type-cast. Is that must be done ?

Any opinions are truely appreciated :)

leppie
  • 115,091
  • 17
  • 196
  • 297

1 Answers1

0

As far as i know "offsetof" macro is defined as ...

It is not the case that it is defined as such. It may be defined like that. In general, performing pointer arithmetic on a NULL pointer leads to undefined behavior, but if your C library happens to do this, then it must be fine on your particular system.

This, by the way, also crashes for me on OS X 10.9 with clang++. It does not crash using offsetof, though. Conclusion: undefined behavior is undefined, implementation details are implementation details, and you are not supposed to rely on them or make assumptions about them.