为什么我们在 C 中创建链表时不使用 calloc() 而不是 malloc()?
Why don't we use calloc() insted of malloc() while creating linked list in C?
当我们在 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()。这有什么区别?
考虑一个更现实的场景:
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()
就有意义了。
如果设置了none结构,那你就不应该白分配内存。
换句话说;对于大多数情况,calloc()
更差(性能)。
当我们在 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()。这有什么区别?
考虑一个更现实的场景:
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()
就有意义了。
如果设置了none结构,那你就不应该白分配内存。
换句话说;对于大多数情况,calloc()
更差(性能)。