Is &*NULL well-defined in C?

  • A+

In what version(s) of the C standards (if any) is the following well-defined?

void foo(void) {     char *nullPtr = NULL;     &*nullPtr; } 

Note that I am not assigning the result to anything - the second line is a simple statement.

This should be a question with an obvious answer, but (as seemingly happens way too often on such questions) I have heard just as many people say the answer is "obviously undefined" as "obviously defined".

On a rather related note, what about the following? Should foo produce a read of c?

extern volatile char c;  void bar(void) {     volatile char *nonnullptr = &c;     &*nonnullptr; } 

(C++ version of the same question: Is &*NULL well-defined in C++?)


While attempts to dereference a null pointer cause undefined behavior, so *nullPtr is illegal, &*nullPtr is perfectly well-defined. According to footnote 102 in the C11 Draft Standard:

Thus, &*E is equivalent to E (even if E is a null pointer),....

This is a result of the fact that, for the unary & operator (§ ¶3):

If the operand is the result of a unary * operator, neither that operator nor the & operator is evaluated and the result is as if both were omitted,....

The C99 Standard has the same language, but this does not appear in the C90 Standard, and my reading of that standard is that &*nullPtr would indeed cause undefined behavior in pre-C99 implementations.

From the C90 Standard (§

The result of the unary & (address-of) operator is a pointer to the object or function designated by its operand....


The unary * operator denotes indirection.... If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

Curiously, I don't see any discussion of this change in the C99 Rationale, though I may just be not finding it.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: