Possible Duplicate:
Is NULL always zero in C?
The C standard states the following for calloc():
The calloc function allocates space for an array of nmemb objects, each of whose size is size. The space is initialized to all bits zero.
with the following caveat relating to all bits zero:
Note that this need not be the same as the representation of floating-point zero or a null pointer constant.
Test program:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
char** list = calloc(10, sizeof(*list));
int i;
for (i = 0; i < 10; i++)
{
printf("%p is-null=%d\n", list[i], NULL == list[i]);
}
free(list);
return 0;
}
I built and executed this program with the following compilers:
- VC7, VC8, VC9, VC10
- gcc v4.1.2, gcc v4.3.4
- Forte 5.8, Forte 5.10
In all cases all bits zero is a NULL pointer (unless I made a mistake in the test program).
What is the reason a NULL pointer is not guaranteed by the C standard to be all bits zero ? Out of curiousity, are there any compilers where all bits zero is not a NULL pointer ?
The com.lang.c FAQ answers this in question 5.16, where it explains why this happens, and question 5.17, where it gives examples of actual machines with nonzero
NULL. A relatively “common” case is for address 0 to be valid, so a different invalid address is selected forNULL. A more esoteric example is the Symbolics Lisp Machine, which does not even have pointers as we know them.So it’s not really a question of choosing the right compiler. On a modern byte-addressable system, with or without virtual memory, you are unlikely to encounter a
NULLpointer that is not address 0.The C standard is carefully designed to accommodate hardware that is downright bizarre, and this is just one the results. Another weird gotcha along the same lines is that it’s possible for
sizeof(void *) != sizeof(int *), but you’ll never see it happen on a byte-addressable architecture.