Search code examples
c++offsetansi-c

Is this valid ANSI C++ code? Trying to generate offsets of structure members at compile-time


Possible Duplicates:
Does the 'offsetof' macro from <stddef.h> invoke undefined behaviour?
dereferencing the null pointer

    #define _OFFS_OF_MEMBER(p_type, p_member) (size_t)&(((p_type *)NULL)->p_member)

    struct a 
    {
             int a, b;
    };

    size_t l = _OFFS_OF_MEMBER(struct a, b);

I had a little chat/conversation with some fellow users, and one of them said that this is dereferencing and accessing the address space near address NULL. I said: taking an address of a member will not access, touch, or read the value of that member. According to standard it is completely safe.

    struct a* p = NULL;
    size_t offset = &p->b; // this may NOT touch b, it is not dereferencing
    // p->b = 0; // now, we are dereferincing: acccess violation time!

Is this always a safe way to calculate offset, or are compilers free to dereference and mess up the memory near address NULL according to standards?

I know there is a safe way to calculate offsets provided by the standard, but I am curious what you have to say about this. All in favor of my explenation: up-vote this question :-)


Solution

  • You're not dereferencing anything invalid here. All that macro does is tell the compiler that a structure of type p_type exists in memory at the address NULL. It then takes the address of p_member, which is a member of this fictitious structure. So, no dereferencing anywhere.

    In fact, this is exactly what the offsetof macro, defined in stddef.h does.

    EDIT:
    As some of the comments say, this may not work well with C++ and inheritance, I've only used offsetof with POD structures in C.