【问题标题】:Why don't we use calloc() insted of malloc() while creating linked list in C? [duplicate]为什么我们在 C 中创建链表时不使用 calloc() 而不是 malloc()? [复制]
【发布时间】:2021-02-08 09:19:21
【问题描述】:
当我们在 C 中创建一个链表时,我们必须动态地分配内存。所以我们可以使用malloc()和calloc(),但大多数时候程序员使用malloc()而不是calloc()。我不明白为什么?
这是一个节点 -
struct node
{
int data;
struct node *next;
};
现在我们正在初始化 ptr -
struct node *ptr = (struct node *)malloc(sizeof(struct node));
现在我们在这里使用 malloc() 那么为什么大多数程序员不使用 calloc() 而不是 malloc()。有什么区别?
【问题讨论】:
标签:
c
linked-list
malloc
dynamic-memory-allocation
calloc
【解决方案1】:
考虑一个更现实的场景:
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;
}
对于此示例,您可以看到 calloc() 可能会无缘无故地消耗 CPU 时间(用零填充内存),因为结构中的每个字段都被设置为有用的值。
如果没有设置少量结构(例如,numberOfGoats 保留为零),那么将该字段设置为零而不是整个设置为零可能会更快。
如果没有设置大量的结构,那么calloc() 可能有意义。
如果没有设置任何结构,那么你不应该白白分配内存。
换句话说;对于大多数情况,calloc() 更差(性能方面)。