Search code examples
clinked-listmallocdynamic-memory-allocationcalloc

Why don't we use calloc() insted of malloc() while creating linked list in C?


When we create a Linked List in C. In that, we have to allocate memory Dynamically. So we can use malloc() and calloc(), but most of the time programmers use malloc() instead of calloc(). I don't understand why?

This is a node -

struct node  
{  
    int data;  
    struct node *next;    
}; 

Now we are intinalizing the ptr -

struct node *ptr = (struct node *)malloc(sizeof(struct node));  

Now here we are using malloc() So why most of the programmers don't use calloc() instead of malloc(). What difference does it make?


Solution

  • 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).