Question:
What’s better/more efficient – calloc or malloc?I want to initialise structs, that refer to other instances of the same struct also
VARIANT 1
Answer:
There are obvious and more subtile problems in your examples:*void name;
is a syntax error.Neither
struct _person* person = calloc(1, sizeof(person));
norstruct _person* person = malloc(sizeof(person));
will allocate the correct amount of memory becausesizeof(person)
will evaluate to the size of the pointerperson
in the definition, not the typeperson
defined as a typedef forstruct _person
.
In both examples, you should the size of the data pointed to by the pointer:
calloc()
or malloc()
, it is much safer to always use calloc()
for these reasons:- the size of the element and the number of elements are separate, thus avoiding silly mistakes in the overall size computation.
- the memory is initialized to all bits zero, which is the zero value of all scalar types on modern systems. This may allow you to simplify the code by omitting explicit initialization of integers and will force initialization to
0
of all extra members added to the structure definition for which the allocation functions might be missing initializers. - for large arrays,
calloc()
is actually faster thanmalloc(size)
+memset(s, 0, size)
, as is documented this answer: https://stackoverflow.com/a/18251590/4593267
If you have better answer, please add a comment about this, thank you!