Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is &*NULL well-defined in C?

Tags:

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++?)

like image 280
TLW Avatar asked Aug 05 '18 04:08

TLW


People also ask

What are the meanings of is?

Definition of is (Entry 1 of 4) present tense third-person singular of be. dialectal present tense first-person and third-person singular of be. dialectal present tense plural of be.

What type of word is is?

Is is what is known as a state of being verb. State of being verbs do not express any specific activity or action but instead describe existence. The most common state of being verb is to be, along with its conjugations (is, am, are, was, were, being, been). As we can see, is is a conjugation of the verb be.

What is meaning of as it is?

Definition of as it is 1 : in the present condition : the way it is Leave everything exactly/just as it is. 2 : with the situation that exists now We have enough to do as it is without your latest orders!

Is in use a word?

Definition of in use : being used All of the computers are currently in use.


1 Answers

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 (§6.5.3.2 ¶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 (§6.3.2.3):

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

and:

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.

like image 166
ad absurdum Avatar answered Feb 10 '23 18:02

ad absurdum