Possible Duplicate:
Is NULL always zero in C?
Following code:
char *p1 = 0;
char *p2 = NULL;
char *p3 = (char *)0;
if (NULL == 0)
printf("the NULL is same as 0\n");
printf("0 : %s\n", 0);
printf("p1 : %s\n", p1);
printf("p1 : %x\n", p1);
printf("&p1 : %x\n", &p1);
printf("NULL : %s\n", NULL);
printf("p2 : %s\n", p2);
printf("p2 : %x\n", p2);
printf("&p2 : %x\n", &p2);
printf("*p2 : %s\n", *p2);
output:
the NULL is same as 0
0 : (null)
p1 : (null)
p1 : 0
&p1 : bf9a0204
NULL : (null)
p2 : (null)
p2 : 0
&p2 : bf9a0208
Segmentation fault (core dumped)
I wonder:
What the (null) stands for?
Does the pointer p1 or p2 point to address 0x0?
Does the statement printf(“p1 : %x\n”, p1); outputs p1 : 0 indicates p1 point to address 0x0?
All these initializatiions
are equivalent. All of them initialize these pointers with null-pointer value of type
char *. The physical representation of that null-pointer value is platform-dependent. It is not guaranteed to be represented by physical0x0address. There’s no way to say what physical address they will “point to” in general.On your platform null-pointer value happens to be represented by physical address
0x0, judging by the output. However, the proper way to print a pointer value withprintfis to either use%pformat specifier, or by converting the pointer value to a suitable integral type. Using%xto print pointers leads to undefined behavior.The
(null)output that you see is the reaction ofprintfto your attempt to use%sspecifier with null pointers. This leads to undefined behavior, but your implementation of standard library apparently decided to save your from worse fate and print(null)instead.In fact, every single
printfstatement in your code sample is composed incorrectly, each leading to undefined behavior.