-1

In the following program, i am getting a runtime error instead of my program printing NULL. May be this is very silly or simple understanding but i do not have right answer. Thanks in advance.

#include<stdio.h>

int main() 
{
   char *p = NULL;
   printf("%c", *p);
   return 0;
}

2 Answers2

4

C doesn't catch you trying to de-reference a null pointer.

If you want to see the value of the pointer (and see whether the pointer is null), use this printf syntax:

   printf("%p\n", p);
rtx13
  • 2,580
  • 1
  • 6
  • 22
  • `printf("%p\n", (void*)p);` is better to avoid invoking undefined behavior. – MikeCAT May 15 '20 at 15:01
  • 1
    @MikeCAT can you provide a reference to why using `char*` instead `void*` results in undefined behaviour? – rtx13 May 15 '20 at 15:03
  • [c - printf("%p") and casting to (void *) - Stack Overflow](https://stackoverflow.com/questions/24867814/printfp-and-casting-to-void) – MikeCAT May 15 '20 at 15:07
  • 1
    @MikeCAT please see [C11 § 6.2.5 ¶ 28](http://port70.net/~nsz/c/c11/n1570.html#6.2.5p28): _A pointer to void shall have the same representation and alignment requirements as a pointer to a character type_, and its footnote _The same representation and alignment requirements are meant to imply interchangeability as arguments to functions, return values from functions, and members of unions_. – rtx13 May 15 '20 at 15:19
2

printf("%c", *p); does not ask printf to print the value NULL. It attempts to use the value pointed to by p. Since p contains a null pointer, it does not point to a valid object.

To print the value of p, use printf("%p", (void *) p);.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312