Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does offsetof require pointer derefence?

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.

like image 876
Ta Thanh Dinh Avatar asked Oct 19 '25 07:10

Ta Thanh Dinh


1 Answers

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.

like image 99
HolyBlackCat Avatar answered Oct 20 '25 20:10

HolyBlackCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!