Reputation: 4881
I understand this code should never be executed but does *(NULL)
compile successfully by the C99 standard ?
#include <stdio.h>
int main(void) {
*(NULL);
return 0;
}
PS: Running it on ideone returns 0 but I do not know the compiler version being used :(
Upvotes: 1
Views: 385
Reputation: 320679
*(NULL)
is always a constraint violation. *(NULL)
as a full expression is "not compilable" in C under any definition of NULL
. NULL
can be defined an integral zero, which is obviously not dereferencible. NULL
can be defined as integral zero cast to void *
type, but dereferencing void *
pointers is illegal in C.
Note: I'm still not entirely sure whether my statement above about dereferencing void *
pointer is correct. Is it a constraint violation or not? The standard does not spell it out explicitly. But at the same time it defines the behavior of unary *
for pointers to functions and pointers to objects only. Meanwhile, void
is not an object type.
If it is indeed legal to dereference void *
pointers, then *(NULL)
by itself would produce undefined behavior (assuming (void *) 0
definition of NULL
). But there is still one context in which *(NULL)
might be valid as a subexpression. It is &*(NULL)
. The language gives special treatment to &*
combination, making it a no-op with well-defined behavior even in situations where *
alone would produce undefined behavior.
Upvotes: 4
Reputation: 145899
*(NULL)
is undefined behavior.
From the horse mouth:
(C99, 6.5.3.2.p4) "If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.87)"
And (emphasis mine):
87): "Among the invalid values for dereferencing a pointer by the unary * operator are a null pointer, an address inappropriately aligned for the type of object pointed to, and the address of an object after the end of its lifetime."
And of course, NULL
is a null pointer:
(C99, 7.17p3) "The macros [..] NULL which expands to an implementation-defined null pointer constant;"
As with all programs that invoke undefined behavior, a compiler has the right to not compile it (see C99, 3.4.3p2).
Upvotes: 0
Reputation: 215497
If NULL
is defined as simply 0
(which is permitted), then *(0)
is a constraint violation and must be diagnosed. If NULL
is defined as ((void *)0)
then *((void *)0)
invokes undefined behavior (by dereferencing a null pointer) and the compiler is not required to issue any diagnostic, but the program is also not required to behave the way you expect it to.
Upvotes: 5