Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address of members of a struct via NULL pointer

Why the following expression is not a (null pointer) runtime error?

typedef struct{
           int a,b,c;
          } st;

st obj={10,12,15};
st *ptr1=&obj;
st *ptr2=NULL;

printf("%d",*(int *)((char*)ptr1+(int)&ptr2->b));
like image 223
Sundara Raghavan Avatar asked Nov 17 '25 10:11

Sundara Raghavan


2 Answers

Because you are performing pointer arithmetic on a NULL pointer which invokes undefined behavior - and that's not required to crash.

actually, in GNU C, &ptr2->b while st *ptr2=NULL; produce the data member 'b' 's byte offset in the struct, it is 4 here

like image 40
guozhu cheng Avatar answered Nov 19 '25 01:11

guozhu cheng



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!