Question:What’s better/more efficient – calloc or malloc?
I want to initialise structs, that refer to other instances of the same struct also
Answer:There are obvious and more subtile problems in your examples:
*void name;is a syntax error.
struct _person* person = calloc(1, sizeof(person));nor
struct _person* person = malloc(sizeof(person));will allocate the correct amount of memory because
sizeof(person)will evaluate to the size of the pointer
personin the definition, not the type
persondefined as a typedef for
In both examples, you should the size of the data pointed to by the pointer:
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
0of all extra members added to the structure definition for which the allocation functions might be missing initializers.
- for large arrays,
calloc()is actually faster than
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!