为什么我们在 C 中创建链表时不使用 calloc() 而不是 malloc()?



当我们在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为零(,那么将该字段设置为零可能会更快,而不是将整个字段设置为0。

如果没有设置大量的结构,那么calloc()是有意义的。

如果没有设置任何结构,那么就不应该白白分配内存。

换句话说;对于大多数场景,calloc()(对于性能(更差。

最新更新