Does the ‘offsetof’ macro from invoke undefined behaviour?

Where the language standard says “undefined behavior”, any given compiler can define the behavior. Implementation code in the standard library typically relies on that. So there are two questions:

(1) Is the code UB with respect to the C++ standard?

That’s a really hard question, because it’s a well known almost-defect that the C++98/03 standard never says right out in normative text that in general it’s UB to dereference a nullpointer. It is implied by the exception for typeid, where it’s not UB.

What you can say decidedly is that it’s UB to use offsetof with a non-POD type.

(2) Is the code UB with respect to the compiler that it’s written for?

No, of course not.

A compiler vendor’s code for a given compiler can use any feature of that compiler.

Cheers & hth.,

Leave a Comment