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 :-)