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:
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 ?
calloc returns a pointer to the first element of the allocated elements. If memory cannot be allocated, calloc returns NULL . If the allocation is successful, calloc initializes all bits to 0.
Most frequently, calloc ing a structure with pointers: they are initialized to NULL.
calloc writes a bit pattern of all-zeros to the allocated memory, but the null pointer value might not be all-bits-zero on some machines (or even just for some types on some machines).
C library function - free() The C library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc.
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 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 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 NULL
pointer 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With