init init - 1 year ago 53
C Question

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
or similar way. How is 0 interpreted into a memory location?


Answer Source

You are allowed to assign 0 to a pointer because NULL is typically defined as 0 cast to a void *. Any other integer value is a type mismatch.

While you can cast some other integer value to a pointer to assign it a value, it rarely makes sense to do so unless you're dealing with an embedded environment where specific memory locations have known uses.

You're getting a segfault not because you're printing the pointer but because you dereference the pointer and attempt to print what it points to. Because the pointer has a NULL value, dereferencing it causes undefined behavior. In this case, it results in a segfault.

To print the pointer, do the following:

printf("%p\n", (void *)p);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download