Consider a more realistic scenario:
struct person {
struct person *next;
char *name;
char *address;
unsigned int numberOfGoats;
};
struct person * firstPerson = NULL;
struct person * lastPerson = NULL;
struct person * addPerson(char *name, char *address, int numberOfGoats) {
struct person * p;
p = malloc(sizeof(struct person));
if(p != NULL) {
// Initialize the data
p->next = NULL;
p->name = name;
p->address = address;
p->numberOfGoats= numberOfGoats;
// Add the person to the linked list
p->next = lastPerson;
lastPerson = p;
if(firstPerson == NULL) {
firstPerson = p;
}
}
return p;
}
For this example, you can see that calloc()
may cost CPU time (filling the memory with zero) for no reason at all because every field in the structure is set to a useful value anyway.
If a small amount of the structure isn't set (e.g. numberOfGoats
is left as zero), then it's still likely to be faster to set that field to zero instead of setting the whole thing to zero.
If a large amount of the structure isn't set, then calloc()
can make sense.
If none of the structure is set, then you shouldn't have allocated memory for nothing.
In other words; for most scenarios, calloc()
is worse (for performance).