Calloc (), pointers and all bits are null

Possible duplicate:
Is NULL always equal to zero in C?

The C standard specifies the value of calloc() :

The calloc function allocates space for an array of nmemb objects, each of which has a size. A space is initialized for all bits 0.

with the following caveat regarding all bits:

Note that this should not be the same as representing a floating point zero or a null pointer constant.

Testing 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 created 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 null bits are NULL pointers (unless I made a mistake in the test program).

What is the reason the NULL pointer NULL not guaranteed by the C standard so that all bits are zero? Out of curiosity, are there compilers where all bits of zero are not NULL pointers?

+7
source share
2 answers

com.lang.c FAQ answers question 5.16 , which explains why this happens, and question 5.17 , which gives examples of real machines with non-zero NULL . A relatively β€œgeneral” case is suitable for address 0, so another invalid address is selected for NULL . A more esoteric example is the Symbolics Lisp Machine, which does not even have pointers as we know them.

So it’s not a matter of choosing the right compiler. In a modern byte-addressable system with or without virtual memory, you are unlikely to encounter a NULL pointer, which is not address 0.

Standard C has been carefully designed to host hardware that is completely strange, and this is just one result. Another weird loot on the same lines is that it is possible for sizeof(void *) != sizeof(int *) , but you will never see that this happens in an architecture with a byte address.

+9
source

Yes, there are some implementations (some of them are exotic), where the internal representation of NULL not bit-zero. This FAQ section C is very interesting (especially these: 1 and 2 ).

+4
source

All Articles