In ANSI C, offsetof is defined as below.
#define offsetof(st, m) \
((size_t) ( (char *)&((st *)(0))->m - (char *)0 ))
Why won't this throw a segmentation fault since we are dereferencing a NULL pointer? Or is this some sort of compiler hack where it sees that only address of the offset is taken out, so it statically calculates the address without actually dereferencing it? Also is this code portable?
It calculates the offset of the member
m
relative to the start address of the representation of an object of typest
.((st *)(0))
refers to aNULL
pointer of typest *
.&((st *)(0))->m
refers to the address of member m in this object. Since the start address of this object is0 (NULL)
, the address of member m is exactly the offset.char *
conversion and the difference calculates the offset in bytes. According to pointer operations, when you make a difference between two pointers of typeT *
, the result is the number of objects of typeT
represented between the two addresses contained by the operands.