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!
We use the calloc function to allocate memory at run time for derived data types like arrays and structures.
calloc() The function calloc() stands for contiguous location. It works similar to the malloc() but it allocate the multiple blocks of memory each of same size.
The calloc function returns a pointer to the beginning of the block of memory. If the block of memory can not be allocated, the calloc function will return a null pointer.
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.
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