Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address of Null pointer?

Tags:

c++

c

I came across the macro below

#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))

I kind of not able to digest this because in c++, when I try to deference a null pointer, I expect an unexpected behaviour... but how come it can have an address? what does address of null mean?

like image 703
Karthick Avatar asked Sep 22 '11 07:09

Karthick


1 Answers

For the purpose of the macro: It assumes that there is an object of type TYPE at address 0 and returns the address of the member which is effectively the offset of the member in the structure.

This answer explains why this is undefined behaviour. I think that this is the most important quote:

If E1 has the type “pointer to class X,” then the expression E1->E2 is converted to the equivalent form (*(E1)).E2; *(E1) will result in undefined behavior with a strict interpretation, and .E2 converts it to an rvalue, making it undefined behavior for the weak interpretation.

which is the case here. Although others think that this is valid. It is important to note that this will produce the correct result on many compilers though.

like image 159
pmr Avatar answered Nov 15 '22 17:11

pmr