#include <stdio.h>
void main ()
{
int* p = NULL;
printf("%d", *p);
}
It prints:
Exception thrown: read access violation.
p was nullptr.
NULL pointers may not be dereferenced.
Doing so invokes undefined behavior, which in this case manifested in your program crashing.
This is documented in section 6.5.3.2p4 of the C standard:
4 The unary
*
operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type "pointer to type", the result has type "type". If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined. 102)102) Thus,
&*E
is equivalent toE
(even if E is a null pointer), and&(E1[E2])
to((E1)+(E2))
. It is always true that ifE
is a function designator or an lvalue that is a valid operand of the unary&
operator,*&E
is a function designator or an lvalue equal toE
. If*P
is an lvalue andT
is the name of an object pointer type,*(T)P
is an lvalue that has a type compatible with that to whichT
points.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.
If you want to print the pointer itself, pass it to printf
without dereferencing it and use the %p
format specifier:
printf("%p\n", (void *)p);
The behaviour of int* p = NULL; *p;
is undefined.
If you want to print out the address of p
, then use "%p"
as the format specifier, and drop the dereference:
printf("%p", (void*)p);
The cast to (void*)
is required in order to match exactly the format specifier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With