Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, why initializing pointer to 0 doesn't give compile time error?

I was playing around with pointers, and I tried to initialize a pointer variable with a value and not a memory location.

If I am initializing a pointer with a non-zero value, and it is clearly giving me a compile time error.

int *p = 1;
main.c:14:14: error: initialization makes pointer from integer without a cast [-Werror=int-conversion]
 int *p = 1;
          ^

However, if I initialize it as value 0, it doesn't give me a compile time error.

int *p = 0; //no compile time error but segmentation fault

Why is this so? Is there a valid memory address like 0? Normally, an address location is shown as 0xffffff or similar way. How is 0 interpreted into a memory location?

Thanks

like image 897
init Avatar asked Sep 13 '25 12:09

init


2 Answers

From the C11 Standard (draft):

6.3.2.3 Pointers

[...]

3 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

like image 96
alk Avatar answered Sep 16 '25 01:09

alk


Usualy 0 represent a "no address" asNULL. When you use it that way you can check:

if (p) {
     doSomthingWith(*p)
}
like image 39
Ohad Eytan Avatar answered Sep 16 '25 03:09

Ohad Eytan