4

I am wondering whether a simple macro offset_of_ requires a pointer dereference of not. For example, a C++ (means that this code will be compiled using a C++ compiler) struct which is declared with packed attribute

struct A {
  int x;
  int y;
} __attribute__(packed);

Suppose that sizeof(int) == 4 in this case, to calculate the offset of y inside A, I wrote a simple macro:

#define offset_of_y (ptrdiff_t)(&(((A*)0)->y))

Can we be sure that the value of this macro is always 4? Is there any pointer dereference from 0 (which may be a UB) when the macro is invoked?

Many thanks for any response.

Ta Thanh Dinh
  • 638
  • 1
  • 5
  • 12
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/176835/discussion-on-question-by-ta-thanh-dinh-does-offsetof-require-pointer-derefence). – Bhargav Rao Jul 26 '18 at 21:53

1 Answers1

4

Accessing something through a null pointer is UB, period.

(Unless the context is unevaluated, but in this case it IS evaluated.)

You probably want offsetof().


In practice your code probably could work, buf formally it's undefined.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/176830/discussion-on-answer-by-holyblackcat-does-offsetof-require-pointer-derefence). –  Jul 26 '18 at 20:40