Some subsurface notes from a week of diving

Linus Torvalds torvalds at linux-foundation.org
Mon Mar 17 08:47:23 PDT 2014


On Mon, Mar 17, 2014 at 8:31 AM, Linus Torvalds
<torvalds at linux-foundation.org> wrote:
>
> [ Same goes for "&*ptr" btw: the "&" operator literally "undoes" the
> access that is implied by the '*', and the result is just "ptr", with
> no implied access, so you can do it even on a NULL pointer ]

Btw, for anybody wondering "Why?".

This is not just some odd special case, it's very much how C pointers
are supposed to behave. Not only is it really convenient to get the
pointer offsets, it's fundamental to the whole language.

So for example, an array dereference in C is obviously "array[index]",
but that is defined to be the same thing as "*(array+index)", to the
point that you can validly write it the other way around (ie since
"*(array+index)" is the same as "*(index+array)", you can also write
it as "index[array]" if you want to confuse people).

And if "&*ptr" made you go "why would anybody write that", then think
about the array syntax: writing "&array[index]" is just another way of
writing "&*(array+index)" which is another way of writing
"array+index". And sometimes that "&array[index]" form is what people
use for clarity, it looks more explicit than the simpler "array+index"
form.

So the address-of operator ("&") very much _undoes_ the access. When
you do "&*ptr", that does not mean "access the object in ptr, and then
take the address of that", no, it really fundamentally means "ptr".
This matters not just if "ptr" is NULL, but also if "ptr" is a
volatile pointer: while "*ptr" normally would force an access to the
object that cannot be compiled away, "&*ptr" simply does not have that
access in the first place.

And the same is very much true of "&ptr->member". In fact, the
"offsetof()" macro is traditionally defined as some variation on

   #define offsetof(s,m) ((size_t)(long)&(((s *)0)->m))

which very *explicitly* has that "NULL pointer offset calculation".

               Linus


More information about the subsurface mailing list