On Sun, 29 Feb 2004, Aaron Walker wrote:
I was just wondering, if I have:
struct my_struct {
char *str1;
char *str2;
};
and then elsewhere do:
struct my_struct *ms = calloc(1, sizeof(struct my_struct));
Would that be the same as doing:
struct my_struct *ms = malloc(sizeof(struct my_struct));
ms->str1 = ms->str2 = NULL;
Nope. In the first case, you're allocating memory for a struct,
and then 'calloc' is initializing all the allocated bits to zero.
In the second case, you're allocating memory for a struct, and then
initializing ms->str1 to NULL and ms->str2 to NULL.
So there are two key differences:
1. NULL != all bits zero. This is a FAQ.
http://www.eskimo.com/~scs/C-faq/q7.31.html
As a corollary, structs may have padding bits, which would not get
initialized to anything in the second case (but would receive 'zero'
bits in the first, along with every other bit). This is also a FAQ,
but is much less relevant to your actual problem.
2. The second snippet invokes undefined behavior if 'malloc'
returns NULL (failure to allocate enough memory). The first snippet
is perfectly well-defined in all cases -- but, as above, it won't do
what you're expecting it to do.
Read the FAQ; there's lots of important stuff there.
HTH,
-Arthur