Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I an get error when trying to print a null pointer

Tags:

c

pointers

#include <stdio.h>
void main ()
{
    int* p = NULL;
    printf("%d", *p);
}

It prints:

Exception thrown: read access violation.
p was nullptr.
like image 614
אביב נח Avatar asked Dec 23 '22 00:12

אביב נח


2 Answers

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 to E (even if E is a null pointer), and &(E1[E2]) to ((E1)+(E2)). It is always true that if E 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 to E. If *P is an lvalue and T is the name of an object pointer type, *(T)P is an lvalue that has a type compatible with that to which T 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);
like image 191
dbush Avatar answered Dec 29 '22 00:12

dbush


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.

like image 43
Bathsheba Avatar answered Dec 28 '22 22:12

Bathsheba