Is there a difference between:
/* code 1 */
struct sample test;
test = malloc(sizeof(struct sample));
Whoops! Corrected the obvious typos below:
/* code 1 */
struct sample *test;
test = malloc(sizeof *test);
memset(test, 0, sizeof *test);
/* code 2 */
struct sample *test;
test = calloc(1, sizeof *test);
Why would code 1 be chosen over code 2? I tend to see many instances of
code 1 in source code and hardly any instances of code 2.
OMMV, but I personally avoid 'calloc', along with some library
functions such as 'memmove', because I think their *exact* effects
are obscure, and I don't ever feel like reading manpages when I
don't have to.
In particular for your example, 'calloc' takes two arguments whose
order matters -- so I'd have to get that right, where with 'malloc'
I don't. Ease of use.
Secondly, 'calloc' tries to set all the newly allocated bytes to zero.
That generally takes O(n) time. Now C in general has a very close
correspondence between C-language statements and machine-level
instructions, and I feel that if I'm going to be performing a very
expensive setup step like "set this whole block to zero," that's
something that should *not* be hidden away inside a library function
call. The 'malloc'/'memset' idiom makes the cost of setting '*test'
to zero slightly more noticeable.
Those are the two big reasons I don't use 'calloc', but there's
one more: it is rarely the right tool for the job.
In fact, *neither* of those fragments is going to do what you want,
in the general case: setting a struct's bytes to all zero isn't the
same as setting each member of that struct to zero, especially when
it comes to pointers and floating-point numbers. There's no easy
way to set each member of a dynamically allocated 'struct' to zero,
though -- you have to do it one-by-one.
HTH,
-Arthur