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
person *new_person() {
struct _person *person = calloc(1, sizeof(person));
person->name = NULL;
person->child = NULL;
return person;
}
VARIANT 2
person *new_person() {
struct _person *person = malloc(sizeof(person));
person->name = NULL;
person->child = NULL;
return person;
}
The struct
typedef struct _person {
*void name;
struct _person *child;
} person;
There are obvious and more subtile problems in your examples:
*void name;
is a syntax error.
Neither 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 person
in the definition, not the type person
defined as a typedef for struct _person
.
This is a pathological example of name shadowing, whereby a local definition hides another definition for the same identifier in an outer scope. Use -Wshadow
to let the compiler detect and report this kind of problem.
In both examples, you should the size of the data pointed to by the pointer:
struct _person *person = calloc(1, sizeof(*person));
Regarding whether to use calloc()
or malloc()
, it is much safer to always use calloc()
for these reasons:
0
of all extra members later added to the structure definition for which the allocation functions might be missing initializing statements.calloc()
is actually faster than malloc(size)
+ memset(s, 0, size)
, as is documented this answer: https://stackoverflow.com/a/18251590/4593267A more general discussion of this topic is this other question: