I know that calloc request memory to be used, writes 0 on all the bits and then returns a pointer to it.
My question is: if I use calloc with a structure that contains pointers, will those pointers have the NULL value or do I have to set them to point to NULL?
struct a{
char * name;
void * p;
}* A;
So basically, will name and p point to NULL after I've used calloc with struct a?
Thanks!
Somehow you've gotten a lot of incorrect answers. C does not require the representation of null pointers to be all-zero-bits. Many people mistakenly think it does, since an integer constant expression with value 0, converted to a pointer, becomes a null pointer.
With that said, on all real-world systems, null pointers are all-zero-bits, and calloc
is a perfectly reasonable way to get a null-pointer-initialized pointer array in the real world.
R.'s answer is good, but I'd like to add the standard quotes to support this, and show a way to 0 initialize your struct that does, in fact, yield NULL pointers.
From N1548 (C11 draft)
7.22.3.2 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.[289]
The footnote then says (emphasis added):
Note that this need not be the same as the representation of floating-point zero or a null pointer constant.
While a null pointer is usually represented as all 0 bits, this representation is not guaranteed. To answer your question directly, no you cannot rely on the calloc()
'd struct's pointers to be NULL
.
If you want to set all contained pointers of a dynamically allocated struct to NULL
you can use the following:
struct a *s = malloc(sizeof *s);
*s = (struct a){0};
C11:
6.7.9.21
If there are fewer initializers in a brace-enclosed list than there are elements or members
of an aggregate, [...] the remainder of the aggregate shall be
initialized implicitly the same as objects that have static storage duration
and
6.7.9.10
... If an object that has static or thread storage duration is not initialized
explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
C requires you to have at least one element inside the braces, which is why I use {0}
instead of {}
. The rest of the elements are initialized according to the above rules, which results in null pointers. As far as I can tell, the rules for this are the same in C11 and C99.
Yes, they will. Similarly if you do this:
static char * a[100];
all the pointers in the array will be NULL.
The ISO C standard for calloc
requires it to initialize everything to 0
. That means that if you end up veiwing memory allocated by calloc
as pointers, it will indeed initially contain NULL (0) pointers.